Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get total length of all items in object with arrays

I want to get the total of all items in object with array. for example

const obj = {
  one: [1, 4],
  two: [4, 6]
}

I should get total of 4.

I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const obj = {
  one: [1, 4],
  two: [4, 6]
}

let total = 0;
const objKeys = Object.keys(obj);

for (let index = 0; index < objKeys.length; index++) {
  total += obj[objKeys[index]].length
}

console.log(total);

Is there a simpler way of doing this?

>Solution :

You could grab the values of your object, which would be an array of arrays of the following shape:

[[1, 4], [4, 6]]

and then flatten this array with .flat() which gives:

[1, 4, 4, 6];

And then grab the .length of that array.

See example below:

const obj = {one: [1, 4],two: [4, 6]}; 

const res = Object.values(obj).flat().length;
console.log(res);

Note, that if your goal is for efficiency, you can use a standard for...in loop to loop the keys of your object, and then add to a total like as shown below. This also avoids the overhead of creating additional arrays to store the keys/values:

const obj = {one: [1, 4], two: [4, 6]};
let total = 0;
for(const key in obj) 
  total += obj[key].length;
console.log(total);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading