Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda