×

JS数组操作方法:find、some、filter和reduce的应用

作者:andy0012022.01.20来源:Web前端之家浏览:4971评论:0
关键词:js

JS数组操作方法:find、some、filter和reduce的应用。

Array.find

Array.find 返回一个对象(第一个满足条件的对象)后停止遍历

const arrTest = [
    { id: 1, name: "a" },
    { id: 2, name: "b" },
    { id: 3, name: "b" },
    { id: 4, name: "c" }
]
 
// 过滤条件
function getName(val) {
    return arrTest => arrTest.name === val
}
// 如果我们是想找到第一个满足条件的数据,应该使用`Array.find`
console.log(arrTest.find(getName("b")))
// { id: 2, name: "b" }

Array.some

Array.some 返回是否满足条件的布尔值

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

// 过滤条件
function getStatus(val) {
    return arrTest => arrTest.status === val
}
// 如果我们需要查找一个数组中是否存在某个数据的时候,使用Array.some直接拿到结果
console.log(arrTest.some(getStatus("success")))
// true

Array.filter

Array.filter 遍历整个Array返回一个数组(包含所有满足条件的对象)

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

// 过滤条件
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" }
// ]

Array.reduce

Array.reduce 为数组的归并方法,使用场景很多,比如求和、求乘积,计次,去重,多维转一维,属性求和等...
本节示例主要实现Array.reduce对一组数据进行条件过滤后,返回一个新的数组

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" }
// ]

与Array.filter返回的数组的不同,filter返回的是原数组中符合条件的对象集合,filter与 Array.map 结合也可以实现上面的结果,为什么使用reduce更好呢?

// Array.map 和 Array.filter 组合

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" }
// ]

结论:同时使用 Array.filter 和 Array.map 的时候,对整个数组循环了 2 遍。第一次是过滤返回一个新的数组,第二次通过 map 又构造一个新的数组。使用了两个数组方法,每一个方法都有各自的回调函数,而且 filter 返回的数组以后再也不会用到。
使用 Array.reduce 同样的结果,代码更优雅。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js20220120a2.html

网友评论文明上网理性发言 已有0人参与

发表评论: