VicJordan VicJordan - 6 months ago 28
jQuery Question

JavaScript - create a unsorted array which contains sum of duplicate elements alongwith unique elements

I am trying to create a new array from existing array. Condition is that if element is duplicate then sum those elements. Please see below example for details as may be I am not able to explain clearly:

Input:

var arrayA = ["2", "1", "4", "2", "5", "1", "3", "2"];


Output:

var arrayB = ["6", "2", "4", "5", "3"];


here arrayB[0] = sum of 2s (2+2+2), arrayB[1] = sum of 1s (1+1)

I tried a lot but not able to figure out how I can achieve this.

Please help!

Answer

You can do it this way

 arrayA = ["2", "1", "4", "2", "5", "1", "3", "2"];
 //make a set 
 var set =  new Set(arrayA);
 var arrayB = [];
 set.forEach(function(a) {
   //for each set find in the original arrayA
   var len = arrayA.filter(function(f) {
     return f == a;
   });
   //push in arrayB set element * number of it occurance in original array
   arrayB.push((+a) * (len.length));
 })
 console.log(arrayB)

Comments