简体   繁体   中英

How to count values inside an nested array in Javascript

I have an nested array as below:

[
  ["States", "Count"],
  ["DISABLE", 13],
  ["DENY", 9],
  ["FAULTY", 11],
  ["OFF", 8],
  ["ON", 20]
];

I want to get the count of all the values inside the nested array's 'count' column.

the returning result should be like:61 (13+9+11+8+20) Is there any way to do this in Javascript/react?

You can use reduce() to find the sum like below code. Before doing that make sure you removed the first one in your array, because it's a string. I am using shift() to remove it. Instead of shift() you can use splice() .

 var a = [ ["States", "Count"], ["DISABLE", 13], ["DENY", 9], ["FAULTY", 11], ["OFF", 8], ["ON", 20] ]; a.shift(); // removing first element var total = a.reduce((sum, item) => sum+=item[1], 0); console.log(total);

If you can change the data structure, you probably want to have something like:

{
  'DISABLE': 13,
  'DENY': 9,
  ...
}

If you can't, this should work:

const count = array.reduce((acc, cur) => acc += cur[1], 0);
const countArr = [
    ["DISABLE", 13],
    ["DENY", 9],
    ["FAULTY", 11],
    ["OFF", 8],
    ["ON", 20]
  ]

  const sum = countArr.reduce((firstParam, secondParam) => {
      const [name, count ] = secondParam
      return firstParam + count
  }, 0) // 61

remove your first element in array then try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM