How to sum all the duplicate numbers in array to one index with TypeScript

1 Answer

0 votes
const mergeDuplicates = (arr: number[]) => {
    const map: Map<number, number> = arr.reduce((accumulator, currentValue) => {
        if (accumulator.has(currentValue)) {
            accumulator.set(currentValue, accumulator.get(currentValue) + 1);
        } else {
            accumulator.set(currentValue, 1);
        };
        return accumulator;
    }, new Map());
    
    return Array.from(map, element => element[0] * element[1]);
};

const arr: number[] = [2, 3, 4, 2, 1, 1, 7, 5, 8, 9, 5, 3];

// 2+2=4, 3+3=6, 4, 1+1=2, 7, 5+5=10, 8, 9

console.log(mergeDuplicates(arr));



/*
run:

[4, 6, 4, 2, 7, 10, 8, 9] 

*/

 



answered Mar 22, 2024 by avibootz
...