首页 > 解决方案 > 在 2 个单独的数组上执行相同的过滤器和映射功能

问题描述

我正在尝试过滤然后映射 2 个单独的数组。通常我会把它们组合起来,但我想把它们分开,以便以后更容易一些逻辑。

基本上,我有 2 个数组:

const arr1 = [ {obj1}, {obj2}, {obj3} ];
const arr2 = [ {obj4}, {obj5}, {obj6} ];

我想在这些数组中运行(2)过滤器和(1),如下所示:

arr1.filter(obj => obj.color !== 'red')
.filter(obj => obj.shape !== 'circle')
.map(obj => {
  //logic
}

但是,我需要运行完全相同的过滤器,而不合并我的两个数组。所以过滤一个新变量[...arr1, ...arr2]是不可能的

我一直在尝试按照以下方式做一些事情:

arr1.concat(arr2).filter.... 

但我不相信concat可以用过滤器处理。

是否有其他数组方法可以帮助我处理这个问题,我似乎无法得到正确的结果

标签: javascriptarraysecmascript-6

解决方案


您最好的选择是可能只是创建一个单独的函数来执行此操作,就像这样......

const arr1 = [ {color: "blue", shape: "triangle"}, {color: "red", shape: "square"}, {color: "green", shape: "circle"} ];
const arr2 = [ {color: "purple", shape: "diamond"}, {color: "yellow", shape: "square"}, {color: "orange", shape: "circle"} ];

const applyFiltersAndMap = (array) => {
  return array.filter(obj => obj.color !== 'red')
              .filter(obj => obj.shape !== 'circle')
              .map(obj => `${obj.color} ${obj.shape}`);
};

console.log(applyFiltersAndMap(arr1));
console.log(applyFiltersAndMap(arr2));

也就是说,我知道您指定您希望将方法分开以实现更复杂的逻辑,但是我仍然建议使用reduce()来限制迭代。

您可以更改方法以获取过滤器表达式列表和映射,并将它们应用到reduce(). 这将保持您的分离/清洁过滤器功能,同时仍然在reduce.

const arr1 = [ {color: "blue", shape: "triangle"}, {color: "red", shape: "square"}, {color: "green", shape: "circle"} ];
const arr2 = [ {color: "purple", shape: "diamond"}, {color: "yellow", shape: "square"}, {color: "orange", shape: "circle"} ];

const applyFiltersAndMap = (array, filters, mapper) => {
  return array.reduce((out,e) => {
    if (filters.every(f => f(e))) out.push(mapper(e)); //filter and map
    return out;
  }, []);
};

const filters = [                                  //your filter functions
  obj => obj.color !== 'red',
  obj => obj.shape !== 'circle'
];
const mapper = obj => `${obj.color} ${obj.shape}`; //your map function

console.log(applyFiltersAndMap(arr1, filters, mapper));
console.log(applyFiltersAndMap(arr2, filters, mapper));

或者,如果您不介意扩展Array.prototype...

const arr1 = [ {color: "blue", shape: "triangle"}, {color: "red", shape: "square"}, {color: "green", shape: "circle"} ];
const arr2 = [ {color: "purple", shape: "diamond"}, {color: "yellow", shape: "square"}, {color: "orange", shape: "circle"} ];

Array.prototype.applyFiltersAndMap = function(filters, mapper) {
  return this.reduce((out,e) => {
    if (filters.every(f => f(e))) out.push(mapper(e)); //filter and map
    return out;
  }, []);
};

const filters = [                                  //your filter functions
  obj => obj.color !== 'red',
  obj => obj.shape !== 'circle'
];
const mapper = obj => `${obj.color} ${obj.shape}`; //your map function

console.log(arr1.applyFiltersAndMap(filters, mapper));
console.log(arr2.applyFiltersAndMap(filters, mapper));


推荐阅读