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

154
Visualizações
Push array of objects that make up a count of 100

I have an array of objects like the following:

const items = [
    {
        'name': 'P1',
        'value': 50
    },
    {
        'name': 'P1',
        'value': 49
    },
    {
        'name': 'P2',
        'value': 50
    },
    {
        'name': 'P3',
        'value': 50
    }
]

I need to add up the values and then push into an array of objects only if the 1 or more objects make up a value total of 100.

Expected output:

const groupedItems = [
  [
    {
        'name': 'P1',
        'value': 50
    },
    {
        'name': 'P1',
        'value': 49
    },
  ],
  [
    {
      'name': 'P2',
      'value': 50
    },
    {
        'name': 'P3',
        'value': 50
    }
  ]
]

What I have tried:

const temp = [];

for (var i = 0; i < items.length; i++) {
  if ((items[i] + items[i + 1]) < 100) {
    temp.push(items[i]);
  }
}

groupedItems.push(temp);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I guess i would approch your solution like this :

Each time retrieving the first array, reducing it and if the sum of the array + the value of your item is less than 100, pushing your item in the array.

Otherwise, pushing a new array in your groupedItems that contains your item.

There might be a better way of doing this but this is the main idea.

const items = [{
    'name': 'P1',
    'value': 50
  },
  {
    'name': 'P1',
    'value': 49
  },
  {
    'name': 'P2',
    'value': 50
  },
  {
    'name': 'P3',
    'value': 50
  }
]

const groupedItems = []

items.forEach(item => {
  if (groupedItems.length > 0) {
  
  const lastArray = groupedItems[groupedItems.length - 1]

    const sumLastArray = lastArray.reduce((total, current) => current.value + total,
      0)

    if (sumLastArray + item.value < 100) {
      lastArray.push(item)
    } else {
      groupedItems.push([item])
    }
  } else {
    groupedItems.push([item])
  }



})

console.log(groupedItems)

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