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

179
Views
Encuentre el mayor de dos objetos según el valor clave Javascript Reducir

He estado tratando durante 3 días seguidos de resolver esto, en este momento ni siquiera sé qué buscar.

Tengo una variedad de objetos, me gustaría obtener la mayor "cantidad_de_oferta" para cada "id_de_elemento" y luego usar el id_de_elemento, la cantidad de oferta y el id_de_oferta en el DOM. Estoy atascado en el primer paso.

 [ { "item_id": "1", "bid_amount": "765432", "bidder_id": "298709" }, { "item_id": "1", "bid_amount": "380", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "545", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "525", "bidder_id": "317740" }, { "item_id": "2", "bid_amount": "505", "bidder_id": "606396" },]
 function getBids() { var request = new XMLHttpRequest(); request.open('POST', '/get_bids.php', true); request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); request.onload = function() { bids = JSON.parse(this.response) bids.reduce(function(prev, curr) { currItemId = curr.item_id currBidAmnt = curr.bid_amount const item_id = (prev[curr.item_id] || []); const prevBidsForId = prev[currItemId]; if (prevBidsForId) { console.log(' a bid for this item exists, now i need to check if the current bid amount is greater than the previous bid amount for this item ') item_id.push(curr) prev[currItemId] = item_id } else { // push current item to prev console.log(' a bid for this item does not exist ') item_id.push(curr) prev[currItemId] = item_id } return prev }, []) }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Aquí hay un breve script basado en .reduce() que filtrará el objeto con la oferta más alta:

 const bids=[ { "item_id": "1", "bid_amount": "765432", "bidder_id": "298709" }, { "item_id": "1", "bid_amount": "380", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "545", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "525", "bidder_id": "317740" }, { "item_id": "2", "bid_amount": "505", "bidder_id": "606396" }]; const highest = Object.values(bids.reduce((a,c)=>{ let aa=a[c.item_id]; if(!aa||c.bid_amount>aa.bid_amount) a[c.item_id]=c; return a }, {})); console.log(highest);

about 4 years ago · Juan Pablo Isaza Report

0

Simplemente puede 'agrupar por' item_id y almacenar simultáneamente la oferta máxima en el objeto agrupado. Aquí usando un bucle for...of pero puede cambiar la lógica directamente a una reduce si lo desea. (Esto almacena todas las ofertas en una matriz codificada por item_id y la oferta max se asigna a una propiedad separada.

 const bids = [{ "item_id": "1", "bid_amount": "765432", "bidder_id": "298709" }, { "item_id": "1", "bid_amount": "380", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "545", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "525", "bidder_id": "317740" }, { "item_id": "2", "bid_amount": "505", "bidder_id": "606396" }]; const bidsById = {}; for (const bid of bids) { (bidsById[bid.item_id] ??= { bids: [], max: bid }).bids.push(bid); if (bid.bid_amount > bidsById[bid.item_id].max.bid_amount) { bidsById[bid.item_id].max = bid; } } for (const [id, { max }] of Object.entries(bidsById)) { console.log(`${id}: ${max.bid_amount}`); }

Si solo desea el bid_amount en el resultado, puede simplificar

 const bids = [{ "item_id": "1", "bid_amount": "765432", "bidder_id": "298709" }, { "item_id": "1", "bid_amount": "380", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "545", "bidder_id": "606396" }, { "item_id": "2", "bid_amount": "525", "bidder_id": "317740" }, { "item_id": "2", "bid_amount": "505", "bidder_id": "606396" }]; const bidsById = bids.reduce((a, { item_id, bid_amount }) => { if (bid_amount > (a[item_id] ??= bid_amount)) { a[item_id] = bid_amount; } return a; }, {}) for (const [id, max] of Object.entries(bidsById)) { console.log(`${id}: ${max}`); }

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!