Group identical values in array

2020-07-11 09:19发布

问题:

I have an array that has some values inside, and I wish to return another array that has the value grouped in to their own arrays.

So the result I am trying to achieve is something like this:

var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6]
var groupedArr =[[1,1],[2,2,2],[3,3],[4,4,4,4],[5],[6]]

回答1:

This proposal works with Array#reduce for sorted arrays.

var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6],
    groupedArr = arr.reduce(function (r, a, i) {
        if (!i || a !== r[r.length - 1][0]) {
            return r.concat([[a]]);
        }
        r[r.length - 1].push(a);
        return r;
    }, []);

document.write('<pre>' + JSON.stringify(groupedArr, 0, 4) + '</pre>');



回答2:

Here you go. By the way, this works with unsorted array as well.

var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6]
var grpdArr = [];

while(arr.length > 0){
    var item = arr[0];
    grpdArr.push(arr.filter(function(val) {
        return val === item;
    }));

    arr = arr.filter(function(val){return val!==item});
}


//console.log(arr, grpdArr);

Well this should do. Pretty straight forward.., You get the elements and then remove them.



回答3:

With forEach and temporary array

var arr = [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 6];
var temp = [];
var res = [];

arr.forEach(function(e) {
    if (temp.slice(-1) == e) temp.push(e);
    else {
        temp = [e];
        res.push(temp);
    }
});

document.write(JSON.stringify(res));



回答4:

This may not be the most optimal version but should do. This also works for unsorted arrays.

function abc(arr) {
  var newObj = new Object();
  for (var i in arr) {
    if (typeof newObj[arr[i]] == 'undefined') {
      newObj[arr[i]] = new Array();
    }
    newObj[arr[i]].push(arr[i]);
  }

  var groupedArr = new Array();

  for (i in newObj) {
    groupedArr.push(newObj[i]);
  }

  return groupedArr;
}

console.log(abc([1, 1, 2, 2, 3, 3, 3, 4, 1]));



回答5:

This is the most straightforward in my mind:

var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6];
var grouped = {}; 
var groupedArr = []; 

//accumulate the values in an object, each key is an array
for (var i = 0; i < arr.length; i++) {
    if (!grouped[arr[i]]) grouped[arr[i]] = []; 
    grouped[arr[i]].push(arr[i]);
}

//loop through all the keys in the object and push the arrays to the master array
var keys = Object.keys(grouped);
for (var i = 0; i < keys.length; i++) {
    groupedArr.push(grouped[keys[i]]);
}

console.log(groupedArr);


回答6:

I think you could use the code below:

var arr = [1,1,2,2,2,3,3,4,4,4,4,5,6]
var groupedArray = [];
var temp = arr.sort();
var tempArray = [arr[0]];
for(var i = 0; i < temp.length - 1; ++i){
    if(temp[i] == temp[i + 1]){
    tempArray.push(temp[i + 1]);
  }else{
    groupedArray.push(tempArray);
    tempArray = [temp[i + 1]];
  }
}
groupedArray.push(tempArray);

Now the groupedArray will contain the Result