我正在尝试将此函数转换为使用reduce。我已经完成了一半。当选择的值为true时,我想知道该元素的索引。
let options = [
{label: 'foo1', selected: false},
{label: 'foo2', selected: true},
{label: 'foo2', selected: false},
{label: 'foo2', selected: false},
{label: 'foo2', selected: false},
];
const obj = options
.map((option, index) => (option.selected ? index : -1))
.filter((val) => val !== -1)[0];结果:1
我的尝试是这样的:
const obj = options.reduce((acc, currentValue, index) => {
const i = currentValue["selected"] ? index : -1;
return acc.concat(i)
}, []); // [-1,1,-1,-1,-1]如何将整个内容更改为使用reduce?
发布于 2019-02-10 12:25:24
在concat()中使用三元值来设置要插入的值。Array#concat()返回更新后的数组,这就是reduce()的返回值。
或者使用spread返回新的数组[...accumulator, selsected ? i :-1]
const res = options.reduce((a, {selected:s}, i) => a.concat(s ? i : -1) , []);
// OR
// const res = options.reduce((a, {selected:s}, i) => [....a,s ? i : -1] , []);
console.log(res)<script>
let options = [
{label: 'foo1', selected: false},
{label: 'foo2', selected: true},
{label: 'foo2', selected: false},
{label: 'foo2', selected: false},
{label: 'foo2', selected: false},
];
</script>
https://stackoverflow.com/questions/54613300
复制相似问题