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
- count of all products ?
- sum of all products ?
*(each object = one product)
-
Could you show the code you have tried, please?Sterling Archer– Sterling Archer2018年05月08日 14:50:53 +00:00Commented May 8, 2018 at 14:50
4 Answers 4
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);
6 Comments
sum calculation in my code...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);
Comments
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)
Comments
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;}