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

115
Vistas
Rearrange object in an array JavaScript

I have PriorityArray as

[1, 2, 3]

and response json as

[ {
Id: 1,
Name:”aaa”,
Priority:1
},
{
Id: 2,
Name:”bbb”,
Priority:1
},
{
Id: 3,
Name:”ssss”,
Priority:2
},
{
Id: 4,
Name:”aaa”,
Priority:2
},
{
Id: 5,
Name:”dddd”,
Priority:1
},
{
Id: 6,
Name:”dddd”,
Priority:3
}]

I want to arrange all objects based on priority in rotation. Products should be arranged in an array like 1,2,3 then again append next products with priority 1,2,3

Expected output:

[ {
Id: 1,
Name:”aaa”,
Priority:1
},
{
Id: 3,
Name:”ssss”,
Priority:2
},
{
Id: 6,
Name:”dddd”,
Priority:3
}
{
Id: 2,
Name:”bbb”,
Priority:1
},
{
Id: 4,
Name:”aaa”,
Priority:2
},
{
Id: 5,
Name:”dddd”,
Priority:1
},
]
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  • Group the response objects by their priority.

  • Then find the group that has highest no. of items in it.

  • And then loop over the grouped array until all elements have been added to the final array.

const priority = [1, 2, 3];
const res = [
  { Id: 1, Name: "aaa", Priority: 1 },
  { Id: 2, Name: "bbb", Priority: 1 },
  { Id: 3, Name: "ssss", Priority: 2 },
  { Id: 4, Name: "aaa", Priority: 2 },
  { Id: 5, Name: "dddd", Priority: 1 },
  { Id: 6, Name: "dddd", Priority: 3 },
];

const resGroupedByPriority = priority.map((p) =>
  res.filter((r) => r.Priority === p)
);

let index = 0;
let maxIndex = Math.max(...resGroupedByPriority.map((p) => p.length));
let ordered = [];

while (index < maxIndex) {
  resGroupedByPriority.forEach((p) => {
    if (p[index]) {
      ordered.push(p[index]);
    }
  });
  index += 1;
}
console.log(ordered);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could take an object for the indices and create a new array and filter it.

const
    order = [1, 2, 3],
    data = [{ Id: 1, Name: 'aaa', Priority: 1 }, { Id: 2, Name: 'bbb', Priority: 1 }, { Id: 3, Name: 'ssss', Priority: 2 }, { Id: 4, Name: 'aaa', Priority: 2 }, { Id: 5, Name: 'dddd', Priority: 1 }, { Id: 6, Name: 'dddd', Priority: 3 }],
    indices = Object.fromEntries(order.map((k, v) => [k, v])),
    result = data
        .reduce((r, o) => {
            r[indices[o.Priority]] = o;
            indices[o.Priority] += order.length;
            return r;
        }, [])
        .filter(Boolean);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A different approach.

const
    order = [1, 2, 3],
    data = [{ Id: 1, Name: 'aaa', Priority: 1 }, { Id: 2, Name: 'bbb', Priority: 1 }, { Id: 3, Name: 'ssss', Priority: 2 }, { Id: 4, Name: 'aaa', Priority: 2 }, { Id: 5, Name: 'dddd', Priority: 1 }, { Id: 6, Name: 'dddd', Priority: 3 }],
    temp = data.reduce((r, o) => {
        (r[o.Priority] ??= []).push(o);
        return r;
    }, {}),
    result = [];

let i = 0, go = true;

while (go) {
    go = false;
    for (const k of order) {
        if (!temp[k].length) break;
        result.push(temp[k].shift());
        go ||= temp[k].length;
    }
}


console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is what I came up with, it's rather crude but works fine.

const testList = [
  { Id: 1, Name: "aaa", Priority: 1 },
  { Id: 2, Name: "bbb", Priority: 1 },
  { Id: 3, Name: "ssss", Priority: 2 },
  { Id: 4, Name: "aaa", Priority: 2 },
  { Id: 5, Name: "dddd", Priority: 1 },
  { Id: 6, Name: "dddd", Priority: 3 },
];

function prioritySort(arr, priority) {
  arr = arr.slice(); //copies the array

  let result = [];
  let p = priority[0];
  let c = 0;

  while (arr.length > 0 || c > 10000) {
    c++;

    for (let curr in arr) {
      if (arr[curr].Priority == p) {
        result.push(arr[curr]);

        arr.splice(curr, 1);

        break;
      }
    }

    if (c == priority.length) {
      p = priority[0];
      c = 0;
    } else {
      p = priority[c];
    }
  }

  return result;
}

console.log(prioritySort(testList, [1, 2, 3]));

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