简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM