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>');
Post a Comment for "Group Sequential Repeated Values In Javascript Array"