我试图过滤,然后映射2个单独的数组。通常情况下我会将它们组合起来,但我想将它们分开,以便稍后更简单地制作一些逻辑。
基本上,我有……
你最好的选择可能只是创建一个单独的功能来做到这一点,就像这样......
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() 。这将保持您的分离/清除过滤器功能,同时仍然使用更有效的数组方法 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 ...
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));