Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to sort and filter this array of hashes using underscore

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}]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!