jkris jkris - 15 days ago 4
Javascript Question

What's the most concise way in javascript to find consecutive dups in an array, sum them up and reiterate?

Example



I have an array of:

const myArr = [1, 1, 1, 3, 2, 2, 4, 3];


If I were pass it to the function it should produce the output like so:

//result: [2, 1, 3, 8, 3]


The consecutive first two
1
s and
2
s were consecutive duplicates so they were summed up.

The first two consecutive
1
s became
2
so it now doesn't match.

The consecutive
2
s became
4
so it matched the next running number and summed up again resulting in an
8


Although the
3
s are duplicate they we're not summed up because they're not consecutive




Bonus




  • It would be great if someone can demonstrate this using javascript's array functions
    map
    or
    reduce
    .

  • Is this possible without any kind of recursion? someone mentioned its possible, then I'd be nice if it didn't use recursion






EDIT



Adding this here because some have already provided answers.

In the case of:

const myArr = [1, 1, 1, 1];
// result: [4]

const myArr = [1, 1, 1, 1, 3, 2, 2, 4, 3];
// result: [4, 3, 8, 3]


Another interesting case that didn't pass my mind:

const myArr = [1, 1, 2, 2];
//result [4, 2] instead of [2,4]


It should check against the new array as soon a change was made

Answer

With the assumption that this will be used only on arrays of numbers, this is simple enough to do with reduce.

function duplicateAddition(input) {
    var last;
    var result = input;
    do {
        last = result;
        result = last.reduce(function (carry, item) {
            if (carry[carry.length - 1] == item) {
                carry[carry.length - 1] *= 2;
            } else {
                carry.push(item);
            }
            return carry;
        }, []);
    } while (last.length != result.length);
    return result;
}