Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Need help with array reduce function

I have a two dimension array which includes productName, and the email of the customer who bought it. example:

[ ["productName", "CustomerEmail"], [productX, xyz@domain.com], [productY, abc@domain.com], [productX, 123@gmail.com], [productZ, 123@yahoo.com] ]

I want to output a summary which should say productX, sold 10 times productY, sold 12 times etc.

I am trying to use array reduce method which works fine as following

const count = fileArray.reduce((count, item) => {

  if (item[0] === "productX") {
    return count + 1}
    else {return count}
    },1);

console.log(`productX is sold ${count}` times)

but the data am working with has 20 products, and am sure there should be a better way instead of keep writing product name as string to compare in each iteration.

May you help?

thank you

1 Answer

Steven Parker
Steven Parker
231,236 Points

I might do it using map, filter and a Set instead of with reduce:

[...new Set(fileArray.map(x => x[0]))].forEach(product => {
    console.log(`${product} is sold ${fileArray.filter(x => x[0] == product).length} times`);
});

Did I just do your school homework?   :see_no_evil: