DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Use Javascript – .map(), .find(), .reduce() and .filter()
Ayekple Clemence
Ayekple Clemence

Posted on • Originally published at anansewaa.com

Use Javascript – .map(), .find(), .reduce() and .filter()

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() function 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
['πŸ”', 'πŸ¦‡', 'πŸ¦‰', 'πŸ¦„', '🐺']
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

.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 }
Enter fullscreen mode Exit fullscreen mode

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 is reduces any given array to a single value. This is done by executing a provided for each value of the array, then the final value of the function is return 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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

.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 }]
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.