Home >Web Front-end >JS Tutorial >Javascript calculates repeated values in a two-dimensional array sample code
Preface
I recently encountered a problem at work. The requirement is to use Javascript to calculate repeated values of a two-dimensional array. For example, there is a two-dimensional array below
[[\'error\',3],[\'error\',5],[\'error\',6],[\'true\',3],[\'true\',1]]
Need Statistical calculation of duplicate items \'error\' and \'true\',
Result after statistical calculation:
[[\'error\',14],[\'true\',4]]
Implementation code:
var arr = [[\'error\',3],[\'error\',5],[\'error\',6],[\'true\',3],[\'true\',1]]; var obj = {}; var result = []; arr.forEach(function(arr){ obj[arr[0]] = obj[arr[0]]? obj[arr[0]] + arr[1] : arr[1]; }); for (var i in obj){ result.push([i,obj[i]]) }
Summary
The above is the entire content of this article. I hope it can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.
For more Javascript calculations of two-dimensional array repeated value sample codes and related articles, please pay attention to the PHP Chinese website!