Skip to main content
fix typo
Source Link
peterSO
  • 3.6k
  • 14
  • 14

I read your iterative (loop) solution. It's complicated; it's hard to read.


Here's a simplified version of your code.

function merge(aop) {
    const sums = [];
    if (aop.length === 0) {
        return sums;
    }

    const str = aop[0][0]aop[0][0];
    let end = sums.push([str, 0]) - 1;

    for (const [str, num] of aop) {
        if (str === sums[end][0]) {
            sums[end][1] += num;
        } else {
            end = sums.push([str, num]) - 1;
        }
    }

    return sums;
}

const example = [ ["A", 3], ["A", 2], ["B", 9], ["C", 1], ["C", 2], ["C", 3], ["D", 2], ["E", 0], ["E", 1] ];

console.log(merge(example));

[ [ 'A', 8 ], [ 'B', 9 ], [ 'C', 6 ], [ 'D', 2 ], [ 'E', 1 ] ]

I read your iterative (loop) solution. It's complicated; it's hard to read.


Here's a simplified version of your code.

function merge(aop) {
    const sums = [];
    if (aop.length === 0) {
        return sums;
    }

    const str = aop[0][0]
    let end = sums.push([str, 0]) - 1;

    for (const [str, num] of aop) {
        if (str === sums[end][0]) {
            sums[end][1] += num;
        } else {
            end = sums.push([str, num]) - 1;
        }
    }

    return sums;
}

const example = [ ["A", 3], ["A", 2], ["B", 9], ["C", 1], ["C", 2], ["C", 3], ["D", 2], ["E", 0], ["E", 1] ];

console.log(merge(example));

[ [ 'A', 8 ], [ 'B', 9 ], [ 'C', 6 ], [ 'D', 2 ], [ 'E', 1 ] ]

I read your iterative (loop) solution. It's complicated; it's hard to read.


Here's a simplified version of your code.

function merge(aop) {
    const sums = [];
    if (aop.length === 0) {
        return sums;
    }

    const str = aop[0][0];
    let end = sums.push([str, 0]) - 1;

    for (const [str, num] of aop) {
        if (str === sums[end][0]) {
            sums[end][1] += num;
        } else {
            end = sums.push([str, num]) - 1;
        }
    }

    return sums;
}

const example = [ ["A", 3], ["A", 2], ["B", 9], ["C", 1], ["C", 2], ["C", 3], ["D", 2], ["E", 0], ["E", 1] ];

console.log(merge(example));

[ [ 'A', 8 ], [ 'B', 9 ], [ 'C', 6 ], [ 'D', 2 ], [ 'E', 1 ] ]
Source Link
peterSO
  • 3.6k
  • 14
  • 14

I read your iterative (loop) solution. It's complicated; it's hard to read.


Here's a simplified version of your code.

function merge(aop) {
    const sums = [];
    if (aop.length === 0) {
        return sums;
    }

    const str = aop[0][0]
    let end = sums.push([str, 0]) - 1;

    for (const [str, num] of aop) {
        if (str === sums[end][0]) {
            sums[end][1] += num;
        } else {
            end = sums.push([str, num]) - 1;
        }
    }

    return sums;
}

const example = [ ["A", 3], ["A", 2], ["B", 9], ["C", 1], ["C", 2], ["C", 3], ["D", 2], ["E", 0], ["E", 1] ];

console.log(merge(example));

[ [ 'A', 8 ], [ 'B', 9 ], [ 'C', 6 ], [ 'D', 2 ], [ 'E', 1 ] ]