提问者:小点点

基于相同项的数组分块


我想根据相同的元素对数组进行切片,这导致了一个2D(分块)数组。 例如,让arr=[10,10,10,10,20,20,20,30],我想要得到以下新的2D数组; [[10,10,10,10],[20,20,20],[30]]或设arr为[2,5,13,13,15,16,16,16],其结果为[[2],[5],[13,13],[15],[16,16,16]]。

我做了一个努力,比如:

设a=[10,10,10,10,20,20,20,30]; 设b=[];

for(let i = 0; i <= a.length; i++) {
  if(a[i] !== a[i+1]) {
  let chunk = a.slice(a.indexOf(a[i]), a.indexOf(a[i + 1]));
    b.push(chunk);
  }
}

console.log(b)输出[[10,10,10,10],[20,20,20],[]]。 如何在最后一个(空)数组中包含30?


共3个答案

匿名用户

假设所有相同的值被分组在一起。

您可以将最后一个索引作为索引的值。

null

let a = [10, 10, 10, 10, 20, 20, 20, 30],
    b = [],
    i = 0;

while (i < a.length) b.push(a.slice(i, i = a.lastIndexOf(a[i]) + 1));

console.log(b);
.as-console-wrapper { max-height: 100% !important; top: 0; }

匿名用户

将它们与一个对象分组

null

arr=[10, 10, 10, 10, 20, 20, 20, 30]
 g={}
 res=[]
 arr.forEach(n => {
   if(!g[n]) res.push(g[n]=[])
   g[n].push(n)
 });
 console.log(res)

匿名用户

null

let arr = [10, 10, 10, 10, 20, 20, 20, 30];
let obj = {};
arr.map(e => {
    obj[e] = obj[e] || [];
    obj[e].push(e);
});
let B = Object.values(obj);
console.log(B);