Detailed explanation of the differences between js array find, some, filter, and reduce

Detailed explanation of the differences between js array find, some, filter, and reduce

Distinguish the differences between the filter, find, some, and reduce methods in Array, and better apply them in daily coding according to their usage scenarios.

Array.find

Array.find returns an object (the first object that meets the condition) and stops traversing

const arrTest = [
    { id: 1, name: "a" },
    { id: 2, name: "b" },
    { id: 3, name: "b" },
    { id: 4, name: "c" }
]

// Filter condition function getName(val) {
    return arrTest => arrTest.name === val
}
// If we want to find the first data that meets the conditions, we should use `Array.find`
console.log(arrTest.find(getName("b")))
// { id: 2, name: "b" }

Array.some

Array.some returns a Boolean value indicating whether the condition is met.

const arrTest = [
    { id: 1, name: "a", status: "loading" },
    { id: 2, name: "b", status: "loading" },
    { id: 3, name: "b", status: "success" }
]

// Filter condition function getStatus(val) {
    return arrTest => arrTest.status === val
}

// If we need to find out whether a certain data exists in an array, use Array.some to get the result directly console.log(arrTest.some(getStatus("success")))
// true

Array.filter

Array.filter traverses the entire Array and returns an array (containing all objects that meet the conditions)

const arrTest = [
    { id: 1, name: "a", status: "loading" },
    { id: 2, name: "b", status: "loading" },
    { id: 3, name: "b", status: "success" }
]

// Filter condition function getStatus(val) {
    return arrTest => arrTest.status === val
}

 
// If we need to filter out all the data that meets the conditions in an array, we should use Array.filter
console.log(arrTest.filter(getStatus("loading")))
// [
// { id: 1, name: "a", status: "loading" },
// { id: 2, name: "b", status: "loading" }
// ]

Array.reduce

Array.reduce is an array merging method, which can be used in many scenarios, such as summing, multiplication, counting, deduplication, converting multi-dimensional data to single-dimensional data, summing attributes, etc.
The examples in this section mainly implement Array.reduce to return a new array after conditionally filtering a set of data.

const arrTest = [
    { id: 1, status: "loading" },
    { id: 2, status: "loading" },
    { id: 3, status: "success" }
]

console.log(
    arrTest.reduce((acc, character) => {
        return character.status === "loading"
            ? acc.concat(
                  Object.assign({}, character, { color: "info" })
              )
            : acc
    }, [])
)
// [
// { id: 1, status: "loading", color: "info" },
// { id: 2, status: "loading", color: "info" }
// ]

Unlike the array returned by Array.filter, filter returns a set of objects that meet the conditions in the original array. The above result can also be achieved by combining filter with Array.map. Why is it better to use reduce?

// Array.map and Array.filter combined console.log(
    arrTest
        .filter(character => character.status === "loading")
        .map(character =>
            Object.assign({}, character, { color: "info" })
        )
)
// [
// { id: 1, status: "loading", color: "info" },
// { id: 2, status: "loading", color: "info" }
// ]

Conclusion: When using Array.filter and Array.map at the same time, the entire array is looped twice. The first time is to filter and return a new array, and the second time is to construct a new array through map. Two array methods are used, each with its own callback function, and the array returned by filter is never used again.
Using Array.reduce gives the same result, but with more elegant code.

This is the end of this article about the detailed explanation of the differences between js array find, some, filter, and reduce. For more related js array find, some, filter, and reduce content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the reduce method of arrays in JavaScript
  • Detailed explanation of JS array Reduce() method and advanced techniques
  • js array method reduce classic usage code sharing
  • 25 advanced uses of JS array reduce that you must know
  • Analysis of the principle and usage skills of JS array reduce() method
  • Sharing the magic of Javascript array method reduce
  • Detailed explanation of the function and usage of JS array Reduce method
  • Parsing JavaScript array method reduce
  • Example analysis of the usage of JS array method reduce
  • JavaScript array reduce common instance methods

<<:  Quickly solve the problem that CentOS cannot access the Internet in VMware

>>:  Why does MySQL database index choose to use B+ tree?

Recommend

Use HTML and CSS to create your own warm man "Dabai"

The final result is like this, isn’t it cute… PS:...

Solution to EF (Entity Framework) inserting or updating data errors

Error message: Store update, insert, or delete st...

How to solve the 2002 error when installing MySQL database on Alibaba Cloud

The following error occurred while installing the...

A detailed introduction to Linux system operation levels

Table of contents 1. Introduction to Linux system...

Solution to mysql error code 1064

If the words in the sql statement conflict with t...

Detailed steps to install MYSQL8.0 on CentOS7.6

1. Generally, mariadb is installed by default in ...

Example code for circular hover effect using CSS Transitions

This article introduces Online preview and downlo...

Use of Vue filters and custom instructions

Table of contents Filters 01.What is 02. How to d...

Ubuntu 18.04 MySQL 8.0 installation and configuration method graphic tutorial

This article shares the installation and configur...

Analysis of Nginx Rewrite usage scenarios and configuration methods

Nginx Rewrite usage scenarios 1. URL address jump...

Analysis and solution of a MySQL slow log monitoring false alarm problem

Previously, for various reasons, some alarms were...