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

150
Vistas
Divide object array elements into groups of n each javascript

I have an Object as below:

const boxOfFruits = {
  apples: [
    {
      name: "Kashmiri",
    },
    {
      name: "Washington",
    },
    {
      name: "Himalayan",
    },
    {
      name: "Fuji",
    }
  ],
  oranges: [
    {
      name: "Nagpur",
    },
    {
      name: "Clementine",
    },
  ],
mangoes: [
    {
      name: "Totapuri",
    },
    {
      name: "Alphonso",
    },
    {
      name: "Langda",
    },
  ],
}

I want to divide these fruits into boxes; maximum of n each, let's say where n is 3 and apples, oranges and mangoes are equally distributed.

So the output in this case would be:

box_1 = [{name: "Kashmiri"}, {name: "Nagpur"},{name: "Totapuri"}];
box_2 = [{name: "Washington"}, {name: "Clementine"},{name: "Alphonso"}];
box_3 = [{name: "Himalayan"},{name: "Langda"}, {name: "Fuji"}];

The type of fruits(apple,oranges,etc)/keys in object can increase/decrease and n is also variable. In case total fruits are less than n, then it would be just 1 box of fruits.

What I have tried so far:

Using Lodash, I am calculating the minimum and the maximum fruits in a single type:

const minFruitType = _.min(Object.values(basket).map((eachBasket: any) => eachBasket.length));

Total teams will the sum of the fruits / n

Will distribute the minimum fruits (l) in the first l boxes and fill the rest with the remaining fruits at every iteration while at the start of every iteration will calculate the minimum type of fruits again.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use Object.values(), array#reduce and array#forEach to transform your object.

const boxOfFruits = { apples: [ { name: "Kashmiri", }, { name: "Washington", }, { name: "Himalayan", }, ], oranges: [ { name: "Nagpur", }, { name: "Clementine", }, ], mangoes: [ { name: "Totapuri", }, { name: "Alphonso", }, { name: "Langda", }, ], },
    result = Object.values(boxOfFruits).reduce((r, arr) => {
      arr.forEach((o,i) => {
        const key =  `box_${i+1}`;
        r[key] ??= r[key] || [];
        r[key].push(o)
      });
      return r;
    },{});
console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

The easiest way would be to use lodash.js's zip() function:

const boxes = _.zip( Object.values(boxOfFruits) );

Note that _.zip() will give you undefined values when the source arrays are different lengths, so you'll need/want to filter those out:

const boxes == _.zip( Object.values(boxOfFruits) )
               .map(
                 box => box.filter(
                   x => x !== undefined
                 )
               );

But that will not distribute the fruits evenly. For that, it shouldn't get much for difficult than this:

function distribute(boxOfFruits, n) {

  const boxes = [];
  const fruits = Object.keys(boxOfFruits);
  
  for ( const fruit of fruits ) {

    let i = 0;
    const items = boxOfFruits[fruit];

    for (const item of items) {
      boxes[i] = !boxes[i] ?? [];
      boxes[i] = boxes[i].push(item);
      ++i;
      i = i < n ? i : 0 ;
    }

  }

  return boxes;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

A modified version of @Nicholas Carey's answer worked for me:

function distribute(boxOfFruits, n) {
  let boxes = [];

  let totalFruits = Object.values(boxOfFruits)
    .reduce((content, current) => content + current.length, 0);
  let maxBoxes = Math.ceil(totalFruits / 4);

  Object.values(boxOfFruits).forEach((fruits) => {
    let i = 0;
    fruits.forEach((fruit) => {
      boxes[i] ??= boxes[i] || [];
      boxes[i].push(fruit);
      ++i;
      i = i < (n+1) ? i : 0;
    });
  });

  // Extra boxes created, redistribute them to
  // starting boxes
  let newBoxes = teams.slice(0, maxBoxes);
  let pendingBoxes = teams.slice(maxBoxes);
  let pendingFruits = pendingBoxes.flat();

  let distributedBoxes = newBoxes.map((eachBox) => {
    let required = n - eachBox.length;
    if (required > 0) {
      eachBox.push(...pendingFruits.splice(0, required));
    }
    return eachBox;
  });

  return distributedBoxes;
}

Code is pretty much the same as Nicholas's accept the below changes:

  1. Directly fetched the values and iterated over those
  2. empty array creation was failing, this way works
  3. and checking on the max box size with n+1 instead of n
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