2

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
  • 1
    Welcome to Stackoverflow! As I'm sure you've read the article about how to ask a good question, you might know that this is not a coding service. Please show what you've tried so far and were you got stuck and we're happy to help! Commented Dec 29, 2015 at 21:55
  • It is a for loop, if check and pushing to arrays. Commented Dec 29, 2015 at 22:06

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.