通过过滤函数划分数组 [英] Dividing an array by filter function
问题描述
我有一个Javascript数组,我希望根据每个元素上调用的函数返回 true
或 false
。从本质上讲,这是一个 array.filter
,但我还想了解过滤 out 的元素。
I have a Javascript array that I would like to split into two based on whether a function called on each element returns true
or false
. Essentially, this is an array.filter
, but I'd like to also have on hand the elements that were filtered out.
目前,我的计划是使用 array.forEach
并在每个元素上调用谓词函数。根据这是真还是假,我将当前元素推送到两个新数组中的一个。是否有更优雅或更好的方法来做到这一点?一个 array.filter
例如,在返回 false
之前,它会将元素推送到另一个数组?
Currently, my plan is to use array.forEach
and call the predicate function on each element. Depending on whether this is true or false, I will push the current element onto one of the two new arrays. Is there a more elegant or otherwise better way to do this? An array.filter
where the will push the element onto another array before it returns false
, for instance?
推荐答案
使用ES6,您可以使用带有reduce的扩展语法:
With ES6 you can make use of the spread syntax with reduce:
function partition(array, isValid) {
return array.reduce(([pass, fail], elem) => {
return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
}, [[], []]);
}
const [pass, fail] = partition(myArray, (e) => e > 5);
或单行:
const [pass, fail] = a.reduce(([p, f], e) => (e > 5 ? [[...p, e], f] : [p, [...f, e]]), [[], []]);
这篇关于通过过滤函数划分数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!