Javascript 基于内部数组条件划分数组
我有这样一个数组:Javascript 基于内部数组条件划分数组,javascript,arrays,Javascript,Arrays,我有这样一个数组: let colors=[ [ 31236780195925 ],[],[],[],[],[ 31236780163157 ],[],[],[ 31236780228693 ],[],[],[],[],[] ] 内部数组值可以不同, 我希望得到如下结构中的结果 let Red=[[ 31236780195925 ],[],[],[],[]]; let Green=[[ 31236780163157 ],[],[]]; let Blue=[[ 31236780228693 ],
let colors=[ [ 31236780195925 ],[],[],[],[],[ 31236780163157 ],[],[],[ 31236780228693 ],[],[],[],[],[] ]
内部数组值可以不同,
我希望得到如下结构中的结果
let Red=[[ 31236780195925 ],[],[],[],[]];
let Green=[[ 31236780163157 ],[],[]];
let Blue=[[ 31236780228693 ],[],[],[],[],[]];
如果您总是希望提取RGB值,因此颜色数组中有3个值。你可以这样做:
const colors = [[31236780195925], [], [], [], [], [31236780163157], [], [], [31236780228693], [], [], [], [], []];
const indexes = [];
colors.forEach((color, index) => {
if (color.length > 0) {
indexes.push(index);
}
});
const red = colors.slice(indexes[0], indexes[1]);
const green = colors.slice(indexes[1], indexes[2]);
const blue = colors.slice(indexes[2]);
- 第一个循环创建
变量中每个数组的索引数组,该数组不是空的colors
- 然后,您可以
在这些索引处对数组进行分割.slice
以防您需要更具动态性的方法。您可以再次循环颜色数组,并使用这些索引创建新的嵌套数组:
const slicedColors = [];
colors.forEach((color, index) => {
if (color.length > 0) {
const nextColorIndex = indexes[indexes.indexOf(index) + 1];
slicedColors.push(colors.slice(index, nextColorIndex));
}
});
const red = slicedColors[0];
const green = slicedColors[1];
const blue = slicedColors[2];
我只是用
reduce
和destructure
实现了它:
const [R, G, B] = colors.reduce((acc, cur, indx) => {
if(cur.length && indx === 0 ) {
acc.push([cur]);
} else if(!cur.length) {
acc[acc.length - 1].push(cur);
} else {
acc.push([cur]);
}
return acc;
}, []);
您可以使用以下解决方案。它检查每个元素的长度,若超过0,则开始填充下一个索引<代码>红色有
[0]
索引,绿色
有[1]
索引,蓝色
有[2]
结果数组索引
var colors=[[31236780195925]、[]、[]、[]、[]、[]、[31236780163157]、[]、[]、[31236780228693]、[]、[]、[]、[]、[]、[]、[];
var res_ar=[];
var i=-1;
colors.forEach(ar=>{
如果(ar.length>0){
i++;
资源推送([]);
}
res_ar[i].推(ar);
})
//控制台日志(res_ar)
console.log(res_ar[0]);
console.log(res_ar[1]);
console.log(res_ar[2])代码>根据什么分割阵列?嗨!请通读一遍,尤其是你在这里的最佳选择是做你的研究,对于相关的话题等等,并尝试一下。如果你在做了更多的研究和搜索后陷入困境,无法摆脱困境,请发布一份你的尝试,并明确指出你陷入困境的地方。人们将乐于提供帮助。从一个值包含内部数组到下一个值包含内部数组