Home > Software engineering >  How to sort and filter this array of hashes using underscore
How to sort and filter this array of hashes using underscore

Time:10-17

I want to use underscore.js in order to take the highest price for each tokenId in the array of hashes below. I would imagine this would require running through the array twice, but perhaps there is a more efficient way. What's the best way to utilize underscore to only grab one hash keyed by tokenId and to select the one with the highest price with the fewest number of iterations through the entire array set?

const data = [
    {
        "tokenId": 1,
        "price": 1.8
    },
    {
        "tokenId": 1,
        "price": 2.0 
    },
    {
        "tokenId": 1,
        "price": 1.9
    },    
    {
        "tokenId": 2,
        "price": 5.0 
    },
    {
        "tokenId": 2,
        "price": 1.0 
    },
    
    {
        "tokenId": 3,
        "price": 1.9
    }    
]

// final result should be
// sortedFiltered = [{tokenId: 1, price: 2.0}, {tokenId: 2, price: 5.0}, {tokenId: 3, price: 1.9}]

CodePudding user response:

A reduce can do it in one iteration. Use the accumulator to keep max price values indexed by tokenId.

const data = [
    {
        "tokenId": 1,
        "price": 1.8
    },
    {
        "tokenId": 1,
        "price": 2.0 
    },
    {
        "tokenId": 1,
        "price": 1.9
    },    
    {
        "tokenId": 2,
        "price": 5.0 
    },
    {
        "tokenId": 2,
        "price": 1.0 
    },
    
    {
        "tokenId": 3,
        "price": 1.9
    }    
]

// one iteration, with a custom function
const maxes = data.reduce((acc, o) => {
  if (acc[o.tokenId] === undefined) acc[o.tokenId] = 0;
  if (acc[o.tokenId] < o.price) acc[o.tokenId] = o.price;
  return acc;
}, {});

console.log(maxes);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related