Home >Web Front-end >JS Tutorial >Javascript calculates repeated values ​​​​in a two-dimensional array sample code

Javascript calculates repeated values ​​​​in a two-dimensional array sample code

高洛峰
高洛峰Original
2017-01-14 10:54:201259browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn