Skip to content Skip to sidebar Skip to footer

Group Sequential Repeated Values In Javascript Array

I have this Array: var arr = ['a','a','b','b','b','c','d','d','a','a','a']; I wish this output: [ ['a','a'], ['b','b','b'], ['c'], ['d','d'], ['a','a','a'], ] Obs.: Not

Solution 1:

Solution with Array.prototype.reduce() and a view to the former element.

var arr = ['a', 'a', 'b', 'b', 'b', 'c', 'd', 'd', 'a', 'a', 'a'],
    result = [];

arr.reduce(function (r, a) {
    if (a !== r) {
        result.push([]);
    }
    result[result.length - 1].push(a);
    return a;
}, undefined);

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

Solution 2:

You can reduce your array like this:

var arr = ['a','a','b','b','b','c','d','d','a','a','a'];

var result = arr.reduce(function(r, i) {
    if (typeof r.last === 'undefined' || r.last !== i) {
        r.last = i;
        r.arr.push([]);
    }
    r.arr[r.arr.length - 1].push(i);
    return r;
}, {arr: []}).arr;

console.log(result);

see Array.prototype.reduce().

Post a Comment for "Group Sequential Repeated Values In Javascript Array"