Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group identical values in array

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]]
like image 999
Emil Mladenov Avatar asked Apr 27 '16 11:04

Emil Mladenov


2 Answers

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>');
like image 159
Nina Scholz Avatar answered Sep 23 '22 20:09

Nina Scholz


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.

like image 45
Karthik RP Avatar answered Sep 25 '22 20:09

Karthik RP