问题描述
只是想知道是否可以使用数组函数(如过滤器)使用解构同时返回语句的否定结果和肯定结果。
类似于以下内容:
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);
所以是做后者的一种速记方式。 似乎在任何地方都找不到关于此的任何信息,因此可能根本不可能。 谢谢!
解决方法
你的想法永远不会像写的那样奏效,因为 filter
的返回必然是一个数组,而不是一个结构。如果你不介意只找到一个值,这个变体很有效:
{ a,b } = [ { a: 'yyy',b: 'yzz' },{ a: 'aww',b: 'azz' } ].find(e => e.a.startsWith('y'))
> a
'yyy'
> b
'yzz'
但更仔细地看,我看到了你真正想要的,所以也许最直接的是:
> a = [ '',' hello ',' ',false,[],[0],[''],[' '],null,undefined,new Array(),1,-1 ]
[
'',[ 0 ],[ '' ],[ ' ' ],-1
]
> { truthish,falsish } = { truthish: a.filter(e => !!e),falsish: a.filter(e => !e) }
{
truthish: [ ' hello ',-1 ],falsish: [ '',0 ]
}
,
您可以使用 .reduce
:
const getTruthysAndFalsys = (array) => {
return array.reduce(
({ truthys,falsys },item) => {
const isTruthy = item.isTruthy
return {
truthys: [
...truthys,...(isTruthy ? [item] : []),],falsys: [
...falsys,...(!isTruthy ? [item] : []),}
},{ truthys: [],falsys: [] }
)
}
const array = [
{ name: 'Item 1',isTruthy: true },{ name: 'Item 2',{ name: 'Item 3',isTruthy: false },{ name: 'Item 4',]
getTruthysAndFalsys(array)
// {
// truthys: [
// { name: 'Item 1',
// { name: 'Item 2',
// { name: 'Item 4',// ],
// falsys: [
// { name: 'Item 3',// }
,
正如@Pointy 建议的那样,您可以通过将元素分成两个数组来避免过滤两次,Array.prototype.reduce()
如下所示:
const input = [1,true,"","foo"];
const [truthies,falsies] = input.reduce(
([truthies,falsies],cur) =>
!cur ? [truthies,[...falsies,cur]] : [[...truthies,cur],[[],[]]
);
console.log(truthies,falsies);