javascriptcodepenarray-reduce

having an issue with Array.reduce(). I have somewhat correct output. But I can't figure out the rest


Here are the instructions:

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:

https://codepen.io/alexiscodes21/pen/wvEVrew?editors=0011


Solution

  • 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);