1

I have an object with some array items, now I have to calculate the length of all items. I got an idea to calculate these items, I declared count = 0 variable, then calculated these items length & added with count variable.

var obj = {
  item_1: ['item1', 'item2', 'item3', 'item4'],
  item_2: ['item1', 'item2', 'item3', 'item4', 'item5'],
  item_3: ['item1', 'item2', 'item3']
}

var count = 0;

Object.entries(obj).map(item => {
  count += item[1].length
})

console.log(count)

My question is: how can I get this result without declaring calculate variable? example: console.log(Object.entries(Obj)....?)

Barmar
  • 741,623
  • 53
  • 500
  • 612
Mina
  • 167
  • 1
  • 3
  • 13

2 Answers2

8

You are looking for reduce:

  Object.values(obj).reduce((sum, subarr) => sum + subarr.length, 0)

This is one of the rare good usecases for it, there are a lot of other cases were reduce actually complicates the code, so going with global variables is sometimes the better approach.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

you can do

[].concat.apply([], Object.values(obj)).length

or using ES6

[].concat(...Object.values(obj)).length

i am just adding one more step to Merge/flatten an array of arrays in JavaScript?

ashish singh
  • 6,526
  • 2
  • 15
  • 35