How to sort data by price in an array with the same field and remove the smallest from the array?

  • 0
    Good day.
    It is not possible to sort the data by price in an array with the same field and remove the smallest one from the array
    [{ name: "Creeper's Cruel Painsaw", price: '2.53', rarity: 'Common' },
    { name: "Creeper's Cruel Painsaw", price: '2.50', rarity: 'Common' },
    { name: 'Cuffs of Oak and Yew', price: '3.94', rarity: 'Rare' },
    { name: 'Cuffs of Oak and Yew', price: '4.99', rarity: 'Rare' },
    { name: 'Curled Root-Staff', price: '2.91', rarity: 'Common' },
    { name: 'Curled Root-Staff', price: '3.33', rarity: 'Common' }]


    I have more than 10 objects with the same name, of which I need to choose the smallest one for the price. And there are thousands of such names, how can you automate this ...? And iterate over the whole array, not just one object or one name
    JavaScript Evangeline Bruce, Aug 20, 2019

  • 1 Answers
  • 0
    const newArr = [...arr]
    .sort((a, b) => a.name.localeCompare(b.name) || (a.price - b.price))
    .filter((n, i, a) => n.name === a[i - 1]?.name);


    if some name value occurs only once, and such objects need not be deleted:



    const newArr = [...arr]
    .sort((a, b) => a.name.localeCompare(b.name) || (a.price - b.price))
    .filter((n, i, a) => n.name === a[i - 1]?.name || n.name !== a[i + 1]?.name);


    if sorting by name is not needed:



    const newArr = [...arr]
    .sort((a, b) => a.price - b.price)
    .filter((n, i, a) => n !== a.find(m => m.name === n.name));


    if sorting by name is not needed and only copies need to be saved:



    const newArr = [...arr].sort((a, b) => a.price - b.price);

    Object
    .values(newArr.reduce((acc, n) => ((acc[n.name] ||= []).push(n), acc), {}))
    .forEach(n => n.length !== 1 && newArr.splice(newArr.indexOf(n[0]), 1));
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!