filter
method and reduce
method are two commonly used methods of JavaScript arrays, and they have some differences in function and usage.
-
filter
method:- Function:
filter
The method is used to filter the elements in the array and return a new array containing elements that meet the specified conditions. - Usage:
filter
The method accepts a callback function as a parameter. The callback function will judge each element in the array. If the return value is the valuetrue
, the element will be added to the new array, otherwise it will not be added. - Example:
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // [2, 4]
- Function:
-
reduce
method:- Function:
reduce
The method is used to perform cumulative calculations on the elements in the array and return a final result. - Usage:
reduce
The method accepts a callback function and an initial value as parameters. The callback function accepts two parameters, the first parameter is the accumulated value (the initial value or the return value of the previous callback function), and the second parameter is the current element. The callback function will calculate each element in the array, and use the calculation result as the cumulative value of the next callback function. - Example:
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // 15
- Function:
Summarize:
filter
The method is used to filter the elements in the array and return a new array.reduce
The method is used to perform cumulative calculations on the elements in the array and return a final result.filter
The return value of the callback function of the methodtrue
is orfalse
, which is used to determine whether to add elements to the new array.reduce
The return value of the callback function of the method is an accumulated value, which is used for the calculation of the next callback function.filter
The method does not change the original array, butreduce
the method can change the original array.
Tool collection: https://aiburgeon.com/siteCollection/