我试图得到每个数组的序列索引,就像我有一个数组的元素,5个数组有多个元素,我想要得到每个数组的第一个索引,然后是第二个,依此类推。
下面是我的数组数据
const arrData = [[1,2,4,6],[3,8,7],[12,13],[],[9,10]];
和我的预期outout
给我解决问题的办法
由于它是一个嵌套数组,您可以遍历并检查每个嵌套数组的第一个元素是否未定义。如果没有,可以将其推入结果数组。我写了函数供你参考。请检查
const arrData = [[1, 2, 4, 6], [3, 8, 7], [12, 13], [], [9, 10]];
function sorter(arr) {
var result = [];
if (arr.length > 0) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > 0) {
if (arr[i][0] !== undefined) {
result.push(arr[i][0]);
}
}
}
}
return result;
}
console.log(sorter(arrData));
我希望这是你所期待的!如果你需要澄清,请联系我。
以下可能有效:
null
const src = [[1,2,4,6],[3,8,7],[12,13],[],[9,10]],
pickByOne = arr => {
const result = [],
{length} = arr.flat()
while(result.length < length){
for(a of arr){
a.length && result.push(a.shift())
}
}
return result
}
console.log(pickByOne(src))
>
使用
使用
使用
使用
null
const arrData = [[1,2,4,6],[3,8,7],[12,13],[],[9,10]];
let res = [], index = 0;
while(true) {
const elementsAtIndex = _.filter(
_.map(arrData, e => e[index]),
e => e!==undefined
);
if(_.isEmpty(elementsAtIndex)) break;
res = [...res, ...elementsAtIndex];
index++;
}
console.log(...res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>