Help us understand the problem. What is going on with this article?

Simplify javascript use .map(), .reduce(), and .filter()

More than 1 year has passed since last update.

.map()

Basically, it takes 2 arguments, a callback and an optional context(will be considered as this in the callback). The callback runs for each value in the array and returns each new value in the resulting array and the resulting array will always be the same length as the original array.

let's say that you have received an array containing multiple objects - each one represent a sudent and you need only the array that containing only the id of each student.

var students = [
   { id: 1, name: 'Pich' },
   { id: 2, name: 'Oudom' },
   { id: 3, name: 'Doe' },
   { id: 4, name: 'John' },
   { id: 5, name: 'Joy' }
];

//output
[1, 2, 3, 4, 5]

We can get the result in many ways like creating empty array then using forEach(), for(...of), or a simple for().

let's see the code:

var studentIds = [];

students.forEach(function (student) {
   studentIds.push(student.id);
});

using .map() instead:

var studentIds = students.map(function (student) {
   return student.id
});

To be more concise with arrow function we can code something like this:

const studentIds = students.map(student => student.id);

.reduce()

It runs a callback for each element of an array and passes the result of this callback(the accumulator) from one array element to the other. The accumulator can be pretty
much anything like integer, string, object, etc. and it must be instantiated or passed when calling .reduce().

let result = arr.reduce(callback);
// Optionally, you can specify an initial value
let result = arr.reduce(callback, initValue);

result — the single value that is returned.
arr — the array to run the reduce function on.
callback — the function to execute on each element in the array.
initValue — an optionally supplied initial value. If this value is not supplied, the 0th element is used as the initial value.

callback function can take four arguments. You will recognize three of the arguments from the map() and filter() methods. The new argument is the accumulator.

accumulator — the accumulator accumulates all of the callbacks returned values.
val — the current value being processed
index — the current index of the value being processed
arr — the original array

Example:

var a = [2, 48, 16]; 
var sum = a.reduce((total, val) => total + val);
sum // 66

.filter()

What if you have an array, but only want some of the elements in it? That’s where .filter() comes in! The .filter() method creates a new array with all elements that pass the test implemented by the provided function.

Let's see the example:

var students = [
   {
     id: 1,
     name: "Adel",
     gender: "girl"
   },
   {
     id: 2,
     name: "Bob",
     gender: "boy"
   },
   {
     id: 3,
     name: "Jonh",
     gender: "boy"
   },
   { 
     id: 4,
     name: "Janny",
     gender: "boy"
   },
   {
     id: 5,
     name: "Dane",
     gender: "girl"
  }
]

We want two arrays now, one for boy and one for girl with .filter():

const g = students.filter(girl => girl.gender === 'girl');
const b = students.filter(boy => boy.gender === 'boy');
phansreypich
Software Engineering student but funny, Like travelling, eating, making friends, technology, I can speak Japanese a little bit. I went to Japan once this year.
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした