Javascript comes with a couple of functions that make things easy. You probably have heard of .map(), .find(), .reduce()and .filter(). But, how and when can we use these functions to simplify our code. I will try and explain with examples of how each of these functions works.

.map()

How does the .map() method work? Here is an example to explain it. Assuming you received a data of array containing multiple objects and each object represent an animal. But you only need an array containing only the emoji of each animal. For this, the map method creates a new array of emoji with the results of the calling function provided on every element in the given array.

let animals = [
  {id: 1, emoji: '🐔', name: 'Chicken'},
  {id: 2, emoji: '🦇', name: 'Bat'},
  {id: 3, emoji: '🦉', name: 'Owl'},
  {id: 4, emoji: '🦄', name: 'Unicorn'},
  {id: 5, emoji: '🐺', name: 'Wolf'}
];

// Expected result
['🐔', '🦇', '🦉', '🦄', '🐺']

We can use for(), .forEach(), or for...of to accomplish this result.
But why will we want to use .map() instead of the for loops? Let’s compare

let emojis = [];

// forEach loop
animals.forEach(animal => {
  emojis.push(animal.emoji)
});

let emojis2 = []

// for..of loop
for(const animal of animals){
  emojis2.push(animal.emoji)
}

let emojis3 = []

// for loop
for(let i = 0; i < animals.length; i++){
  emojis3.push(animals[i].emoji)
}

In the code above we created an empty array to enable us to store the result from the various loops. But this can be simply accomplished with .map() without declaring an empty array beforehand.

let emojis = animals.map(animal => animal.emoji);

.find()

The .find() method is an easier way to find and return the first element of a provided array, under a defined testing function.
However, .find() only return a single element and if nothing is found it returns a value of undefined.
So if the goal is to the return a single value, use .find().

Usage

// Array of strings

const birds = [
  'duck',
  'eagle',
  'penguin',
  'owl',
  'parrot'
];

const output = birds.find(bird => bird.startsWith('p'));

console.log(output); // penguin

// Array of objects

const birds = [
  { name: 'duck', count: 6 },
  { name: 'eagle', count: 5 },
  { name: 'penguin', count: 10 },
  { name: 'owl', count: 7 },
  { name: 'parrot', count: 3 }
];

const output = birds.find(bird => bird.name === 'owl');

console.log(output) // { name: 'owl', count: 7 }

const output2 = birds.find(bird => bird.count > 3)
console.log(output2) // { name: 'duck', count: 6 }

Notice that the example for an Array of strings returned only the first element that matches the defined testing function. To return or find multiple values use .filter() instead.

.reduce()

The .reduce() method reduces any given array to a single value. This is done by executing a reducer function provided for each value of the array, then the final value of the function returns into an accumulator. The resulting accumulator is output in a single value.

let numbers = [1, 2, 3, 4];
const output = numbers.reduce((accumulator, value) => accumulator + value, 0)
console.log(output) // 10

In the example above, we sum the value of the array. Now let’s try another example with an array of objects.

let animals = [
  {id: 1, emoji: '🐔', name: 'Chicken', number: 5},
  {id: 2, emoji: '🦇', name: 'Bat', number: 6},
  {id: 3, emoji: '🦉', name: 'Owl', number: 9},
  {id: 4, emoji: '🦄', name: 'Unicorn', number: 2},
  {id: 5, emoji: '🐺', name: 'Wolf', number: 10}
];

let numberAnimalReducer = (accumulator, currentValue) => accumulator + currentValue.number;

const totalAnimals = animals.reduce(numberAnimalReducer, 0)

console.log(totalAnimals) // 32

.filter()

Unlike .find() that returns the first element that passes the defined testing function, .filter() create a new array of elements that pass the testing function. Meaning if there are no elements in the array that pass the test, the resulting array that will be returned will be empty.

// Array of strings

const birds = [
  'duck',
  'eagle',
  'penguin',
  'owl',
  'parrot'
];

const output = birds.filter(bird => bird.startsWith('p'));

console.log(output); // [ "penguin", "parrot" ]

// Array of objects

const birds = [
  { name: 'duck', count: 6 },
  { name: 'eagle', count: 5 },
  { name: 'penguin', count: 10 },
  { name: 'owl', count: 7 },
  { name: 'parrot', count: 3 }
];

const output = birds.filter(bird => bird.name === 'owl');

console.log(output) // [{ name: 'owl', count: 7 }]

const output2 = birds.filter(bird => bird.count > 6)
console.log(output2) // [{ name: 'penguin', count: 10 }, { name: 'owl', count: 7 }]

With .filter() any element that passes the testing function gets sent to the new array. Similarly, when dealing with array objects any object that passes the testing function get pushed into the new array.

Conclusion

Using javascript array methods will not only make your life easier but also makes you write clean as well. I have another article on Javascript Shorthand Coding Techniques that discussed 18 different shorthand techniques in Javascript.

Other Resources

During my research for this article I found these helpful articles:

Comments to: Use Javascript – .map() .find() .reduce() and .filter()

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Login

Welcome to Typer

Brief and amiable onboarding is the first thing a new user sees in the theme.
Join Typer
Registration is closed.
%d bloggers like this: