map(), filter(), reduce() in JavaScript with simple examples

Mohith Gupta
5 min readApr 18, 2023

--

Photo by Kevin Ku on Unsplash

If you are not using these functions yet, you are missing out on a lot.
Let’s learn the differences between these functions in today’s post.

Map

The map() method creates a new array from an existing one and returns it. It applies the provided function to all the elements of the existing array.

const result_array = array.map((element, index, array) => {
// any action to be performed on the element
})

Only the element is mandatory which represents the currently selected element of the array, the other arguments are optional. We can perform some action on existing elements and receive the processed resultant array of it.

Example

Student’s marks are increased by 5 due to an extra score for a question.

const marks_of_students = [15, 20, 25, 30];
const marks_after_extra_score = marks_of_students.map(mark => mark + 5);
console.log(marks_after_extra_score); // [20, 25, 30, 35]

Filter

The filter() method takes each element in an array and applies the conditional function provided against it and returns an array.
If the condition returns
>> True, the element gets appended to the resultant array.
>> False, the element is left out.

const result_array = array.filter((element, index, array) => {
// condition to apply on the element
})

Only elementis required and the others are optional.
The syntax for filter is the same as that of map, except the fact that the callback function should return true or false for the element to be kept or left out respectively. Take a look at the example below.

Examples

A very common example of this function filter → filtering out odd/even numbers from an array.

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(number => number % 2 === 0);
console.log(evens); // [2, 4]

Now let’s use filter() to get details of the students whose grades are above certain requirements.

const students = [
{ name: 'Mohith’, grade: 69},
{ name: 'Lalith’, grade: 90 },
{ name: 'Madhu’, grade: 85 },
{ name: 'Praneeth’, grade: 70},
{ name: 'Munna’, grade: 75},
];const pass_mark = 70;
const students_who_passed = students.filter(student => student.grade >= pass_mark);
return students_who_passed;
// {name: 'Lalith’, grade: 90}
// {name: 'Madhu’, grade: 85}
// {name: 'Praneeth’, grade: 70}
// {name: 'Munna’, grade: 75}

Reduce

The reduce() method takes the elements and runs the provided reducer function on all of them and always reduces an array of values down to a single value. You get a value as an output, not an array.
Of course, you can make that value be an array/object/… but you get my point (See the second example below if you don’t understand how)

const final_value = array.reduce((prev_result, element, index, array) => {
}, initial_value)

This function accepts four arguments, but only the first two are most often used.

  • prev_result → returned value of the previous iteration
  • element → current item in the array
  • index → index of the current item
  • array → the original array
  • The initial_value argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.

Examples

A simple example is the Sum of elements of an array.

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce(cumulative_sum, number) {
return cumulative_sum + number;
}, 0); // initial value will be 0

// => 0 +1 returns 1 for next iteration
// => 1 +2 returns 3 for next iteration
// => 3 +3 returns 3 for next iteration
// => 6 +4 returns 10 as final answer

console.log(sum); // 10

Now let’s use reduce() to count the frequency of words in a sentence.
Let’s consider a quote as our sentence

const good_quote = “The way to get started is to quit talking and begin doing”;
const words = good_quote.split(" ");
console.log(words) // ['The', 'way', 'to', 'get', 'started', 'is', 'to', 'quit', 'talking', 'and', 'begin', 'doing'];

Notice how we will be passing an empty object {} as the initialValue parameter for the counter_obj_with_previous_words So the final result will be an object.

const words_count = words.reduce((counter_obj_with_previous_words, word) => {
if(!counter_obj_with_previous_words[word])
// if it does not have the word in it
counter_obj_with_previous_words[word] = 1;
else
// if it has the word already
counter_obj_with_previous_words[word]++;

return counter_obj_with_previous_words; // return it so that it can be used for the next word
}, {}) // initial value is an empty object

console.log(words_count) //{ "The": 1,
// "way": 1,
// "to": 2,
// "get": 1,
// "started": 1,
// "is": 1,
// "quit": 1,
// "talking": 1,
// "and": 1,
// "begin": 1,
// "doing": 1 }

Only practice can help you understand these functions better and their use cases. It will be easier once you get your hands on them.

Please consider showing your appreciation by providing feedback and suggestions in the comment section.

If you are pleased too much, you can always buy me a coffee 😉

buy me a coffee link

Any Comments/Suggestions are much appreciated. That is it for the day…

--

--

Mohith Gupta

A Better Person than Yesterday, I guess? In the process of Learning