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

高洛峰
Release: 2017-01-14 10:54:20
Original
1201 people have browsed it

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]]
Copy after login

Need Statistical calculation of duplicate items \'error\' and \'true\',

Result after statistical calculation:

[[\'error\',14],[\'true\',4]]
Copy after login

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]]) }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!