在javascript中,通过一个函数过滤并映射数组?

问题描述 投票:1回答:1

在Java语言中,Array.filter()接受一个数组,并根据特定条件对其进行过滤。

const a = [1,2,3,4,5].filter(el => el > 3);
console.log(a);

结果:[4,5]

Array.map()接受一个数组并返回一个新的相等长度的数组,通常会在过程中改变原始元素。

const a = [1,2,3,4].map(el => el + 10);
console.log(a);

结果:[11,12,13,14,15]

我的问题是,除了结合这两个功能:

let a = [1,2,3,4,5].filter(el => el > 3).map(el => el + 10);
console.log(a);

是否有一种有效的方法来过滤和变异数组,而该数组不像大多数Array.forEachforfor..in例程那样涉及多行代码?我知道Array.filter().map()效率很高,我只是想知道是否可以进一步简化它。

javascript arrays
1个回答
1
投票

使用Array.prototype.reduce一次完成所有过滤和映射。

let a = [1,2,3,4,5].reduce((arr, el) => el > 3 ? arr.concat(el + 10) : arr, []);
console.log(a);

您也可以创建自己的mapIf polyfill函数。

// Reduce Only
if (Array.prototype.mapIf === undefined) {
  Array.prototype.mapIf = function(predicateFn, applyFn) {
    return this.reduce((ref, el) => predicateFn(el) ? ref.concat(applyFn(el)) : ref, []);
  };
}

// Filter + Map
if (Array.prototype.mapIf === undefined) {
  Array.prototype.mapIf = function(predicateFn, applyFn) {
    return this.filter(predicateFn).map(applyFn);
  };
}


let a = [1,2,3,4,5].mapIf(el => el > 3, el => el + 10);
console.log(a);
© www.soinside.com 2019 - 2024. All rights reserved.