【发布时间】:2021-08-28 12:51:18
【问题描述】:
只是想知道是否可以使用数组函数(如过滤器)通过解构同时返回语句的负数和正数结果。
类似于以下内容:
let {truthys, falsys} = arr.filter(a => {
return //magical statement that returns truthy's and falsy's?
});
代替:
let truthys = arr.filter(item => item.isTruthy);
let falsys = arr.filter(item => !item.isTruthy);
所以是后者的一种简写方式。 似乎在任何地方都找不到有关此的任何信息,因此可能根本不可能。 谢谢!
【问题讨论】:
-
您可以使用
.reduce()创建一个包含两个数组的对象。 -
.filter()返回 一个 值数组。如果您传递谓词,则对其进行解构没有多大意义。你可以做的是 group 通过谓词结果返回一个带有{ "true" : /* items that passed the predicate test */, "false": /* items that did not pass the predicate test */ }的对象,然后解构为const {true: truthys, false: falsys} = groupedValues -
谢谢!都会尝试一下:)
-
见georg's
partitionimplementation here 这基本上就是你所需要的。您可以将其称为parition(arr, x => !!x)(或parition(arr, Boolean),如果您愿意)。这是分区为索引为1和0的数组,但如果您想分区为具有键true和false的对象,方法是相同的。我个人更喜欢后者,因为它更清楚result.true是条件返回true但最终无关紧要的所有结果。 -
const [thruthys, falsys] = partition(arr, item => item.isTruthy)带有适当的辅助函数(参见副本)是标准方法。如果你已经有一个groupBy助手,比如lodash 的那个,你也可以使用const {true: truthys, false: falsys} = _.groupBy(arr, item => !!item.isTruthy)。
标签: javascript arrays filter destructuring shorthand