javascript - 在 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
可以用过滤器处理。
是否有其他数组方法可以帮助我处理这个问题,我似乎无法得到正确的结果
解决方案
您最好的选择是可能只是创建一个单独的函数来执行此操作,就像这样......
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));
推荐阅读
- ruby - 使用 Mobility Gem 进行语言切换
- javascript - MSAL 和 passport-azure-ad 无法验证令牌
- javascript - 敲除输入类型编号检测向上或向下以从 observableArray 添加或删除项目
- .htaccess - mod_rewrite 后找不到文件夹
- javascript - 如何规范输入电子邮件?
- sql - 汇总数字,一些在范围内
- qt - Qml 组件未在 xcb 平台上正确加载
- antlr - 如何在 ANTLR 中启用 orExpression 和 andExpression 规则的组合?
- r - 即使 R 中缺少分类值,也从多个数据帧创建一行
- php - Yii2:如何自定义重置密码表单(查看)