Home  >  Article  >  Web Front-end  >  What is the difference between map() and reduce() in JavaScript?

What is the difference between map() and reduce() in JavaScript?

不言
不言Original
2019-01-09 11:53:445109browse

map() and reduce() are both methods that can process arrays, but their uses are slightly different. The biggest difference is that map() can generate some processing results as new arrays. This article Let’s take a look at the detailed content of the article.

What is the difference between map() and reduce() in JavaScript?

For example, if you want to create a new array that doubles the numbers stored in the array, you can write it as follows.

var numbers = [1,2,3,4,5];
var result = numbers.map(function(num) {
  return num * 2;
})
console.log(result);

The running result is

What is the difference between map() and reduce() in JavaScript?

In this example, map() will be performed on an array containing numeric values.

You can see that each element of the array is returned 2 times within the function.

From this, the execution result shows that an array with twice the original value can be generated.

Strictly speaking, it's not possible to do the same thing using reduce(), but if you use map(), you can do it efficiently with a very simple description.

Regarding the use of the reduce() method, you can refer to: How to use reduce() in JavaScript

The above is the detailed content of What is the difference between map() and reduce() in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn