Akhil

Akhil

🔥😋Add a pinch of sugar to JavaScript .map(), .filter(), and .reduce()

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

In simple words, call map() on an array with a callback function that takes each element of your array and does something that it is asked to, and at the end, it returns the result of all the runs as a new array.
Example:

// return the square of elements of an array
const original = [2, 4, 5, 7]
const squared = original.map(function(element){
    return element**2;
})

console.log(squared);
// [4, 16, 25, 49]

// or we can use an arrow function to make it look simple
const arrow_squared = original.map(el => el**2)

console.log(arrow_squared);
// [4, 16, 25, 49]

It looks fine for this example but in a real-world scenario, our function could be way too complex, and even with an arrow function, it could span multiple lines. We can make it dead simple by following the example below.

when syntax sugar is applied 😋 😋

function getFullName(name_array){
  return(name_array.join(" "));
}

// an array containing first_name, last_name as arrays
const users = [
  ['akhil', 'gautam'],
  ['rakesh', 'patra'],
  ['gourav', 'modi']
];

const names = users.map(getFullName); // just put the name/reference of the function

console.log(names);
// ["akhil gautam", "rakesh patra", "gourav modi"]

So we just created a different function that we send as a callback to map().
Please note, we are not passing any arguments to the function. This same syntactic sugar can be applied to the .filter() and .reduce() as well.


.reduce()

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

It reduces an array to a single output using the callback function.

when syntax sugar is applied 😋 😋

function sum(a, b) {
    return a+b;
}

const costs = [123, 456, 789, 1256];
const total = costs.reduce(sum);

console.log(total);
// 2624

.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

when syntax sugar is applied 😋 😋

function isEven(el){
    return el % 2 === 0;
}

const numbers = [12, 75, 78, 77, 13, 89];
const evens = numbers.filter(isEven);

console.log(evens)
// [12, 78]

Thanks for reading. There will be a series coming soon on Svelte.js very soon in which I will be building micro-apps in every post to give an insight on Svelte.js.

 
Share this
Proudly part of