简体   繁体   中英

Javascript reduce for certain objects within an array of objects

I'm having a little problem here with counting array of object values... The code I have below works just fine but what if I want to target only certain objects within the reduce function?

Basically, something like an SQL WHERE function, so

newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2));

would be

newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2)) WHERE item.type === "c";

You know, something similar to this. How can I achieve something like this?

Thank you.

Here is how you could do it with filter() . filter() returns an array where the function passed to it returns true. This has the effect of only retuning items of type 'c'.

 var cart = [ {type:'c', cost:20.00, amm: 10}, {type:'d', cost:20.00, amm: 1}, {type:'d', cost:20.00, amm: 2}, {type:'c', cost:1.00, amm: 5}, {type:'a', cost:20.00, amm: 7}, ] let newcost = cart.filter(i => i.type === 'c') // only c type items .map(item => item.cost * item.amm) .reduce((prev, next) => prev + next) .toFixed(2); console.log(newcost) 

Also, you didn't ask, but the map() call is extraneous — you don't really need it and it causes an extra loop through your data (you could also just do the test in reduce() and leave out the filter() although that might start to impact readability):

 var cart = [ {type:'c', cost:20.00, amm: 10}, {type:'d', cost:20.00, amm: 1}, {type:'d', cost:20.00, amm: 2}, {type:'c', cost:1.00, amm: 5}, {type:'a', cost:20.00, amm: 7}, ] let newcost = cart.filter(i => i.type === 'c') .reduce((prev, next) => prev + next.cost * next.amm, 0) .toFixed(2); console.log(newcost) 

Add your conditional first in the reduce function. If the element doesn't match your conditional, just return the accumulator first without modifying it.

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