Here are the instructions:
Pretend that there is no Array.filter() method. Use Array.reduce() to filter out only the objects from the provided array with a price property of 10 or over.
Pretend there there is no Array.filter() method, only Array.reduce(). How would you use Array.reduce() to mimic the filter method, thus that from the array below, you can create a new array composed of only the objects from the original array that contain a price property of 10 and over? Part of the code has been completed for you. Complete the rest by uncommenting the return statement on line 36 and writing the code for what to return when cur.price is >= 10.
This is what the expected output should be:
https://i.sstatic.net/kLVJP.png
This is what I have so far:
const gems = [
{ type: 'amethyst', price: 8 },
{ type: 'turquoise', price: 50 },
{ type: 'selenite', price: 2 },
{ type: 'topaz', price: 10 },
{ type: 'emerald', price: 500 }
]
const gemsOverTen = gems.reduce((acc, cur) => {
if (cur.price < 10) return acc;
if (cur.price >= 10) {
return {
...acc,
"type": cur.type, "price": cur.price
}};
}, []);
console.log(gemsOverTen);
Here's my codepen as well:
const gems = [
{ type: 'amethyst', price: 8 },
{ type: 'turquoise', price: 50 },
{ type: 'selenite', price: 2 },
{ type: 'topaz', price: 10 },
{ type: 'emerald', price: 500 }
]
const gemsOverTen = gems.reduce((acc, cur) => {
if (cur.price < 10) return acc;
return [
...acc,
{
"type": cur.type,
"price": cur.price
}
];
}, []);
console.log(gemsOverTen);
if you do not need a fresh copy:
const gems = [
{ type: 'amethyst', price: 8 },
{ type: 'turquoise', price: 50 },
{ type: 'selenite', price: 2 },
{ type: 'topaz', price: 10 },
{ type: 'emerald', price: 500 }
]
const gemsOverTen = gems.reduce((acc, cur) => {
if (cur.price < 10) return acc;
return [
...acc,
cur
];
}, []);
console.log(gemsOverTen);
or just use push
const gems = [
{ type: 'amethyst', price: 8 },
{ type: 'turquoise', price: 50 },
{ type: 'selenite', price: 2 },
{ type: 'topaz', price: 10 },
{ type: 'emerald', price: 500 }
]
const gemsOverTen = gems.reduce((acc, cur) => {
if (cur.price >= 10) acc.push(cur);
return acc;
}, []);
console.log(gemsOverTen);