Skip to content
Advertisement

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.: Notice that I dont want group all the repeat values. Only the sequential repeated values.

Can anyone help me?

Advertisement

Answer

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().

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement