Group sequential repeated values in Javascript Arr

2019-07-16 02:38发布

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?

2条回答
来,给爷笑一个
2楼-- · 2019-07-16 03:02

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>');

查看更多
够拽才男人
3楼-- · 2019-07-16 03:10

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

查看更多
登录 后发表回答