Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
Looping through array of objects and reducing on multiple key/pairs

I have a large array of objects and I am trying to consolidate to where I have one array of objects that looks like below: Each item(ex:banana) will be in 2 separate objects as I am trying to aggregate all buy orders and sell orders, and these are different prices/data.

I have tried grabbing the unique pairings (banana, apple, orange, etc.) and mapping through that and inside another map of the data, but I can't figure it out.

let uniquePairing = Array.from([...new Set(data.map(item => item["name"]))])


**let data = [{
name:'banana,
price:( average cost)
type:buy
items: ( total bananas)
fee: ( total fees)
},
{
name:'banana,
price:( average cost)
type:sell
items: ( total bananas)
fee: ( total fees)
},
{ apples...
]**

Example of data

let data = [
{
name:"banana",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:2,
type: "sell",
fee: 0.5,
items:25
},
{
name:"apple",
price:1,
type: "buy"
fee: 0.5
items:25
},
{
name:"apple",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:2,
type: "sell",
fee: 0.5,
items:25
}
]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If I understand your question correctly, you can use the reduce function:

let uniquePairing = data.reduce((total, currentObj) => {
  const name = currentObj.name,
  type = currentObj.type;

  // Group by both `type` and `name`
  let relatedObj = total.find(obj => obj.name === name && obj.type === type);
  if (!relatedObj) {
    total.push({
    ...currentObj,

    // Adding `totalPrice` and `objCount` to track the cost average
    totalPrice: currentObj.price,
    objCount: 1
  })
} else {
  relatedObj.totalPrice += currentObj.price;
  relatedObj.objCount++;
  relatedObj.price = relatedObj.totalPrice / relatedObj.objCount;
  relatedObj.items += currentObj.items;
  relatedObj.fee += currentObj.fee;
}

  return total;
}, []);
about 4 years ago · Juan Pablo Isaza Relatório

0

You could do it like this:

   let data = [
{
name:"banana",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:2,
type: "sell",
fee: 0.5,
items:25
},
{
name:"apple",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:2,
type: "sell",
fee: 0.5,
items:25
}
]

const getFruitData = (fruits, fruit) => fruits.filter(fr=> fr.name===fruit.name && fr.type=== fruit.type)

const getTotal = (fruits, field) => fruits.reduce((acc,cur)=> acc+=cur[field], 0)

const isRegistered = (fruits, value) => fruits.some(fruit=> fruit.type === value.type && fruit.name===value.name)

const getFruits = (fruits) => {
  return fruits.reduce((acc, cur)=> {
if(isRegistered(acc, cur)){
  return acc
}
acc.push({name: cur.name, type: cur.type})
return acc
  }, [])
}

function mergeData(arr){
  const fruits = getFruits(arr)
  return fruits.map(fruit=> {
const data = getFruitData(arr, fruit)
return {
  name: fruit.name,
  price: getTotal(data, "price"),
  type: fruit.type,
  fee: getTotal(data, "fee"),
  items: getTotal(data, "items")
}
  })
}

console.log(mergeData(data))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda