Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - 根据内部数组条件划分数组(Divide array based on inner array conditions)

I have an array like :(我有一个像这样的数组:)

let colors=[ [ 31236780195925 ],[],[],[],[],[ 31236780163157 ],[],[],[ 31236780228693 ],[],[],[],[],[] ] inner array values can differ, I want result like in the following structure(内部数组值可以不同,我想要类似以下结构的结果) let Red=[[ 31236780195925 ],[],[],[],[]]; let Green=[[ 31236780163157 ],[],[]]; let Blue=[[ 31236780228693 ],[],[],[],[],[]];   ask by Zon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following solution.(您可以使用以下解决方案。)

It checks length of each element and if it becomes more then 0 it starts to fill next index.(它检查每个元素的长度,如果长度大于0,它将开始填充下一个索引。) Red has [0] index, Green has [1] index, Blue has [2] index of resultant array.(Red具有[0]索引, Green具有[1]索引, Blue具有[2]所得数组的索引。) var colors=[ [31236780195925],[],[],[],[],[ 31236780163157 ],[],[],[ 31236780228693 ],[],[],[],[],[] ]; var res_ar = []; var i = -1; colors.forEach(ar => { if (ar.length > 0) { i++; res_ar.push([]); } res_ar[i].push(ar); }) // console.log(res_ar) console.log(res_ar[0]); console.log(res_ar[1]); console.log(res_ar[2]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...