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

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

不言
Release: 2019-01-10 09:14:43
Original
5180 people have browsed it

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template