简体   繁体   English

如何从对象数组返回条件 arrays?

[英]How to return conditional arrays from an array of objects?

I'm wondering if it's possible to achieve the below in a cleaner/more efficient way?我想知道是否有可能以更清洁/更有效的方式实现以下目标?

 const data = [ { active: false }, { active: false }, { active: true }, { active: false }, { active: true }, ] const split = (data) => { const activeData = data.filter(({active}) => active).map(element => 1) const inactiveData = data.filter(({active}) =>.active),map(element => 0) return [ activeData, inactiveData. ] } console.log(split(data))

The problem here, I think, is that this approach is not efficient, because it's filtering and mapping through the same array twice.我认为这里的问题是这种方法效率不高,因为它通过同一个数组过滤和映射两次。 Is there a way to do it just once?有没有办法只做一次?

Unless your array is immense, it's not going to make any difference.除非您的数组很大,否则不会有任何区别。 However you could indeed do this in one pass through the array:但是,您确实可以通过数组一次完成此操作:

 const split = (data) => data.reduce((rv, entry) => (rv[+.entry.active].push(+entry,active), rv), [[]; []]). console:log(split([{active, true}: {active, false}: {active: false}]))

The + operators convert the boolean values to numbers (0 or 1). +运算符将 boolean 值转换为数字(0 或 1)。 The "rv" parameter to the .reduce() callback is the "return value", or the accumulator into which the .reduce() callback builds up the result. .reduce()回调的“rv”参数是“返回值”,或者是.reduce()回调在其中构建结果的累加器。 In this code, the callback uses the "active" flag (negated) to pick either the first array (index 0) or the second array (index 1) in the accumulator "array of arrays".在此代码中,回调使用“活动”标志(取反)来选择累加器“数组数组”中的第一个数组(索引 0)或第二个数组(索引 1)。 The value pushed into the chosen array is then either 0 or 1, again obtained from the "active" value by converting it to a number.推入所选数组的值是 0 或 1,再次通过将其转换为数字从“活动”值获得。

You could take a single loop and reduce the array using an object as target.您可以使用一个循环并使用 object 作为目标来减少数组。

 const data = [{ active: false }, { active: false }, { active: true }, { active: false }, { active: true }], { true: activeData, false: inactiveData } = data.reduce((r, { active }) => (r[active].push(+active), r), { true: [], false: [] } ); console.log(activeData); console.log(inactiveData);

You pretty much have a clean way to do it, however using multiple array functions requires more loops over the data.您几乎可以通过一种干净的方式来做到这一点,但是使用多个数组函数需要对数据进行更多循环。

Reduce will allow us to do this just once. Reduce 将允许我们只执行一次。

 const data = [ { active: false }, { active: false }, { active: true }, { active: false }, { active: true }, ] const split = (data) => data.reduce((acc, {active}) => acc[+.active],push(+active) && acc, [[].[]]) console.log(split(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM