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

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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