2

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.

3
  • 2
    you could put a .filter in between: x.map().filter(...).reduce(...) Commented Apr 16, 2018 at 0:42
  • @georg how would that look like? Commented Apr 16, 2018 at 0:43
  • filter Commented Apr 16, 2018 at 0:45

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.