The difference between filter method and reduce method

filtermethod and reducemethod are two commonly used methods of JavaScript arrays, and they have some differences in function and usage.

  1. filtermethod:

    • Function: filterThe method is used to filter the elements in the array and return a new array containing elements that meet the specified conditions.
    • Usage: filterThe method accepts a callback function as a parameter. The callback function will judge each element in the array. If the return value is the value true, 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]
      
  2. reducemethod:

    • Function: reduceThe method is used to perform cumulative calculations on the elements in the array and return a final result.
    • Usage: reduceThe 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
      

Summarize:

  • filterThe method is used to filter the elements in the array and return a new array.
  • reduceThe method is used to perform cumulative calculations on the elements in the array and return a final result.
  • filterThe return value of the callback function of the method trueis or false, which is used to determine whether to add elements to the new array.
  • reduceThe return value of the callback function of the method is an accumulated value, which is used for the calculation of the next callback function.
  • filterThe method does not change the original array, but reducethe method can change the original array.

Tool collection: https://aiburgeon.com/siteCollection/

insert image description here

Guess you like

Origin blog.csdn.net/qq_25741071/article/details/132583166