我有一个数组数组,我想获取一个元素索引数组。我从这个开始:
[
[1,2,3],
[-1],
[-1],
[4,5,6],
[-1],
[],
[]
]
我想要:
[1,2,4]
某些元素可能尚未填充(随着时间的推移它们将被填充),但是我想指定哪些元素故意为空。这就是-1的含义(我可以很容易地使用null)。
我确定filter是正确的选择,但是我不想要该元素;我只想要元素的索引。
我确定我可以通过一些循环和迭代来做到这一点,但这似乎是过大了。
您可以使用Array#reduce
的第三个参数来访问每个元素的索引,如果当前元素与您的flag变量匹配,则可以使用回调有条件地扩展结果数组。
Array#reduce
话虽如此,您的原始版本以及您建议使用const result = [
[1,2,3],
[-1],
[-1],
[4,5,6],
[-1],
[],
[]
].reduce((a, e, i) => e.length === 1 && e[0] === -1 ? a.concat(i) : a, []);
console.log(result);
而不是null
[-1]
似乎不太容易出错。这是为此工作的代码:
可能多一些手册,但非常容易理解。
const emptyIdxes = [
[1,2,3],
[],
[],
[7,8,9],
[]
].reduce((a, e, i) => e.length ? a : a.concat(i), []);
console.log(emptyIdxes);
您也可以使用let input = [
[1,2,3],
[-1],
[-1],
[4,5,6],
[-1],
[],
[]
];
let output = [];
// Loop over original array
input.forEach(function(item, index){
// If length of current item is 1 and that one item is the "deliberately
// empty" indicator, push its index into result array
item.length === 1 && item[0] === -1 ? output.push(index) : null;
});
console.log(output);
功能