This is the first day of my participation in Gwen Challenge
Distinguish the differences between filter, find, some, and reduce methods in Array, and better apply them in daily coding according to their application scenarios.
Array.find
Array.find returns an object (the first one that meets the criteria) and stops traversal
const arrTest = [ { id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "b" }, { id: 4, name: Function getName(val) {return arrTest => arrtest. name === val}Copy the code
Array.find 'console.log(arrtest.find (getName("b"))) // {id: 2, name: "b"}Copy the code
Array.some
Array.some returns a Boolean value for whether the condition is met
const arrTest = [ { id: 1, name: "a", status: "loading" }, { id: 2, name: "b", status: "loading" }, { id: 3, name: Function getStatus(val) {return arrTest => arrtest. status === val}Copy the code
Console. log(arrtest. some(getStatus("success"))) // trueCopy the code
Array.filter
Array.filter Returns an Array containing all objects that meet the criteria for traversing an Array.
const arrTest = [ { id: 1, name: "a", status: "loading" }, { id: 2, name: "b", status: "loading" }, { id: 3, name: "b", status: Function getStatus(val) {return arrTest => arrtest. status === val} Array.filter console.log(arrtest.filter (getStatus("loading"))) // [// {id: 1, name: "a", status: "loading" }, // { id: 2, name: "b", status: "loading" } // ]Copy the code
Array.reduce
Array.reduce is an Array merging method, which can be used in many scenarios, such as summing, multiplying, counting, deduplicating, converting from multidimensional to one-dimensional, attribute summing, etc.
In this example, array. reduce filters a group of data conditionally and returns a new Array
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" }
// ]
Copy the code
Filter, unlike Array returned by array. filter, returns a collection of qualified objects in the original Array. Combining filter with array. map can also achieve the above results.
Console. log(arrtest. filter(character => character.status === "loading") => Object.assign({}, character, { color: "info" }) ) ) // [ // { id: 1, status: "loading", color: "info" }, // { id: 2, status: "loading", color: "info" } // ]Copy the code
Conclusion: Using both array. filter and array. map loops through the entire Array twice. The first time the filter returns a new array, and the second time the map constructs a new array. Two array methods are used, each with its own callback function, and the array returned by Filter is never used again. Using the same result with array.reduce, the code is more elegant.