3 回答
TA贡献1848条经验 获得超2个赞
Boolean 转换为 Number 变为 0 或 1,可以使用逗号运算符将其缩短:
const companyList = [ { name: 'amazon', isIntermediary: false },
{ name: 'microsoft', isIntermediary: false },
{ name: 'talentsearch', isIntermediary: true },
{ name: 'talent global', isIntermediary: true },
{ name: 'taleo', isIntermediary: true } ]
const companies = companyList.reduce((a, v) => (a[+v.isIntermediary].push(v), a), [[], []])
console.log(companies)
TA贡献1846条经验 获得超7个赞
它并不是最易读的单行,但我认为这正是您所要求的。
const companyList = [{
name: 'amazon',
isIntermediary: false
},
{
name: 'microsoft',
isIntermediary: false
},
{
name: 'talentsearch',
isIntermediary: true
},
{
name: 'talent global',
isIntermediary: true
},
{
name: 'taleo',
isIntermediary: true
}
];
const companies = companyList.reduce((acc, c) => c.isIntermediary ? [acc[0], [...acc[1], c]] : [[...acc[0], c], acc[1]], [[], []]);
console.log(companies)
TA贡献1820条经验 获得超9个赞
通过您的代码,这就是您想要的(使用三元来选择是 index0还是1)
const companyList = [
{
name: 'amazon',
isIntermediary: false
},
{
name: 'microsoft',
isIntermediary: false
},
{
name: 'talentsearch',
isIntermediary: true
},
{
name: 'talent global',
isIntermediary: true
},
{
name: 'taleo',
isIntermediary: true
}
];
const companies = companyList.reduce(
(acc, curr) => [!curr.isIntermediary ? [...acc[0], curr] : [...acc[0]], curr.isIntermediary ? [...acc[1], curr] : [...acc[1]]],
[[], []]
);
console.log(companies)
添加回答
举报