Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to sum all the duplicate numbers in array to one index with Node.js

1 Answer

0 votes
const mergeDuplicates = arr => {
    const map = 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 = [8, 2, 3, 4, 2, 1, 1, 7, 5, 9, 5, 3];

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

console.log(mergeDuplicates(arr));



/*
run:

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

*/

 



answered Mar 22, 2024 by avibootz
edited Mar 22, 2024 by avibootz
...