Justin Valdez
Justin Valdez

Reputation: 47

Using filter and reduce JS

I am trying to use filter and reduce to get the total price of Bob's purchases for a little practice on higher order functions I'm doing. I'm given

const purchases = [{"owner":"Barry","price":103},{"owner":"Bob","price":75},
{"owner":"Bob","price":73},{"owner":"Barry","price":57},{"owner":"Barry","price":128},
{"owner":"Bob","price":119},{"owner":"Barry","price":133},{"owner":"Barry","price":27},
{"owner":"Barry","price":138},{"owner":"Bob","price":68},{"owner":"Bob","price":50},
{"owner":"Barry","price":9},{"owner":"Bob","price":123},{"owner":"Bob","price":135},
{"owner":"Barry","price":30},{"owner":"Barry","price":129},{"owner":"Barry","price":38},
{"owner":"Bob","price":133},{"owner":"Barry","price":109},{"owner":"Bob","price":115}]

Use a high order method to create to get the sum of bobsTotal.

This is what I am thinking. I am able to filter bob's purchases into an array, but I am having trouble getting the total price now. I have my reduce section commented out for now for log purposes.

let bobsTotal = purchases.filter(total=>total=purchases.owner="Bob")//.reduce((total, price) => total + price)
console.log(bobsTotal)

Any advice would be great or any other ways to do this would be great.

Upvotes: 1

Views: 107

Answers (1)

Matt Ellen
Matt Ellen

Reputation: 11612

You're very close.

filter's callback needs to be a function that returns true or false.

reduce's callback's arguments are aggregate (because you are aggregating a list into one thing) and current value, and you'll want to set a default value of 0, to have something to sum from.

const purchases = [{"owner":"Barry","price":103},{"owner":"Bob","price":75},
{"owner":"Bob","price":73},{"owner":"Barry","price":57},{"owner":"Barry","price":128},
{"owner":"Bob","price":119},{"owner":"Barry","price":133},{"owner":"Barry","price":27},
{"owner":"Barry","price":138},{"owner":"Bob","price":68},{"owner":"Bob","price":50},
{"owner":"Barry","price":9},{"owner":"Bob","price":123},{"owner":"Bob","price":135},
{"owner":"Barry","price":30},{"owner":"Barry","price":129},{"owner":"Barry","price":38},
{"owner":"Bob","price":133},{"owner":"Barry","price":109},{"owner":"Bob","price":115}]

let bobtot = purchases.filter(p => p.owner === 'Bob').reduce((sum, p) => sum+p.price, 0);

console.log('bob\'s total:', bobtot);

Upvotes: 1

Related Questions