SoFunction
Updated on 2025-03-06

JavaScript array method filter and reduce

Preface

In the newly added array method of ES6, multiple traversal methods are included, including filters and reduces for filtering

filter

The filter method mainly used to filter arrays. During use, the original array will not be changed. At the same time, elements that meet the filter conditions will be placed into a new array for return.

/***
    * @item array element
    * @index traversal array subscript
    * @thisArr Current array
    */
let arr1 = [1, 2, 3, 4, 5];
  let newArr1 = ((item, index, thisArr) => {
    (item);
    (index);
    (thisArr);
    return item > 2;
  })
  (arr1);
  (newArr1);`

After running the above code, you can see that the original array arr1 has not changed, and newArr1 is used to receive an array that meets the filter criteria.

// [1, 2, 3, 4, 5]  arr1
// [3, 4, 5]    newArr1

reduce

Unlike traversal methods such as map and filter, the syntax of reduce is more special.

grammar:

(function(total,currentValue,currentIndex,thisArr){},initValue);
@functionThe callback function is the first parameter,
  • Total is returned as the return value or the initial value
  • CurrentValue The element currently traversed by currentValue
  • CurrentIndex Current traversal element subscript
  • thisArr is the array of the currently executed operation.
  • initValue is the initial value passed to the function

Array sum

// Sum of arrayslet arr1 = [1, 2, 3, 4, 5]
let totals = (function (prev, next) {
    (prev);
    (next);
    return prev + next;
}, 0)
(totals)

Filter whether the first letter contains the b letter

let arr = ['beep', 'boop', 'foo', 'bar'];
(((acc, val) => (val[0] === 'b' && (val), acc), []));

// Advanced whether each number contains 'b'((acc, val) =>
           (('b') >-1 && (val), acc),
           [])

In addition to array summing, reduce can also handle array deduplication and traverse maximum value and minimum value.

At the same time, it can also be used as a higher-order function for other functions to call.

Conclusion

Reduce and filter are new methods for array additions in ES6. They are often encountered in interviews and development. These two functions can be combined with other new methods such as maps to process some more complex data.

This is the end of this article about JavaScript array methods filter and reduce. For more related JavaScript filter and reduce content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!