1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<script type="text/javascript"> var DataValues = [ [ 'john', 10 ], [ 'john', 20 ], [ 'Doe', 30 ], [ 'john', 30 ], [ 'john', 4 ], [ 'Doe', 40 ] ]; var sum = {},result; for (var i=0, c; c = DataValues[i]; ++i) { if ( undefined === sum[c[0]] ) { sum[c[0]] = c; } else { sum[c[0]][1] += c[1]; } } result = Object.keys(sum).map(function(val) { return sum[val]}); document.write(result); document.write("<br><br>"); document.write("JSON Stringfy Values: ",JSON.stringify(result)); </script> |
Also Read: for-Each In JavaScript With Example
Here we create a program to find the Sum of all duplicate values in an array using JavaScript.
In the above source code, first, we define an indexed array where we want to find duplicate values of an array.
Now, we define two variables sum
and result
. Then we loop through the defined array with the condition.
Here we also use the JavaScript map function to do the sum of the array values.
Also Read: How to Convert JSON to Array PHP
Now. we print the complete result with JSON stringify and normal value.
Use the complete source code according to your requirement and let me if you are facing any issues.
Running Example Of Sum of all duplicate values in an array using JavaScript
See the Pen How to find sum of all duplicate values in an array using JavaScript by Bikash Panda (@phpcodertech) on CodePen.
Happy Coding..!