hamidreza nikoonia
hamidreza nikoonia

Reputation: 2165

working with nested object

I think this is silly question and simple but I can't find any result in google and other resource

I have array of object like this

 const myArr = [
     [{
         id: 1,
         price: 200,
     }, {
         id: 2,
         price: 900,
     }, {
         id: 3,
         price: 100,
     }],
     [{
         id: 5,
         price: 100,
     }]
 ];

In other word I have an array and my array contain some array and each of inner array contain some object inside them

 arr [ [ {},{},{} ] ,   [ {} ]    ]

now I want get two thing

  1. count of all products ?
  2. sum of all products ?

*(each object = one product)

Upvotes: 0

Views: 59

Answers (4)

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

ES6

You can also use reduce method of array to get the required result

reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

DEMO

const myArr = [[{id: 1,price: 200,}, {id: 2,price: 900,}, {id: 3,price: 100,}],[{id: 5,price: 100,}]];
  
let result = myArr.reduce((r,v)=>{
  r.count += v.length;
  r.sum += v.reduce((total,{price}) => total+price,0);
  return r;
},{count:0,sum:0}) 

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You can use concat to wrap all objects within one single array.

Apply length property in order to find out the number of objects in the array and then reduce method to get the sum.

const myArr = [ [ { id:1, price:200, }, { id:2, price:900, }, { id:3, price:100, } ], [ { id:5, price:100, } ] ];

arr = myArr.reduce((acc, arr) => acc.concat(arr), []);
sum = arr.reduce((acc, item) => acc + item.price, 0);
console.log('count ' + arr.length);
console.log('sum ' + sum)

Upvotes: 2

Faly
Faly

Reputation: 13356

You can use spread to flat the array:

var myArr = [
 [
   { 
     id:1,
     price:200,
   },

   { 
     id:2,
     price:900,
   },

   { 
     id:3,
     price:100,
   }
 ],

[
  { 
     id:5,
     price:100,
   }
]
];

var arr = [].concat(...myArr);
console.log('Length: ', arr.length);
var sum = arr.reduce((m, o) => m + o.price, 0);
console.log('Sum: ', sum);

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

Flatten to a single array by spreading into Array.concat().

Use Array.reduce() to get the sum.

The count is flattened array's length.

const myArr = [[{"id":1,"price":200},{"id":2,"price":900},{"id":3,"price":100}],[{"id":5,"price":100}]];

const flattened = [].concat(...myArr);
const count = flattened.length;
const sum = flattened.reduce((s, o) => s + o.price, 0);

console.log('count', count);
console.log('sum', sum);

Upvotes: 4

Related Questions