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

137
Visualizações
restructure position of array elements

I have an array called myArray with objects as elements. What I'm trying to achieve is to restructure the position of the array elements without having two objects with the same key next to each other. The method I'm using right now starts to work but messes up after going halfway. How can I achieve this? Thanks in advance.

what I'm trying to achieve: finalArray = [{ "morning": "..." }, { "evening": "..." }, { "morning": "..." }, { "evening": "..." }, { "morning": "..." }, { "evening": "..." }, { "morning": "..." }, { "evening": "..." }, { "evening": "..." }, { "evening": "..." }]

const myArray = [{
  "morning": "23_6557"
}, {
  "evening": "7665_908"
}, {
  "evening": "545_787"
}, {
  "evening": "8774_957"
}, {
  "morning": "434_6447"
}, {
  "morning": "775_67"
}, {
  "evening": "4554_8774"
}, {
  "evening": "224_74"
}, {
  "evening": "43_112"
}, {
  "morning": "32_47"
}]

orderedArray = []
unOrderedArray = []

myArray.forEach((obj) => {
  //if the orderedArray is empty push a random array to it
  if (orderedArray.length == 0) {
    orderedArray.push(obj)
  }

  Object.keys(obj).forEach((key) => {
    //get the last element in the orderedArray and check if its key is equal to the new obj key
    if (Object.keys(orderedArray.at(-1))[0] != key) {
      //get a random object from myArray with key not equal to last orderedArray object key and push it to orderedArray
      orderedArray.push(obj)
    } else {
      //get a random object from myArray with key equal to last orderedArray object key and push it to unOrderedArray
      unOrderedArray.push(obj)
    }
  });
});

const finalArray = orderedArray.concat(unOrderedArray)
console.log(finalArray)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way is to first group the data by property, and then alternate between the groups to extract an element:

const myArray = [{"morning": "23_6557"}, {"evening": "7665_908"}, {"evening": "545_787"}, {"evening": "8774_957"}, {"morning": "434_6447"}, {"morning": "775_67"}, {"evening": "4554_8774"}, {"evening": "224_74"}, {"evening": "43_112"}, {"morning": "32_47"}];

// Create a map keyed by the properties
const map = new Map(myArray.map(o => [Object.keys(o)[0], []]));
// Populate the arrays that are associated by those properties
for (const o of myArray) map.get(Object.keys(o)[0]).push(o);
// Extract the arrays from this map
const groups = [...map.values()];

// Alternate between the groups to pull objects from them
const result = [];
while (groups.length) {
    const group = groups.shift();
    result.push(group.shift());
    if (group.length) groups.push(group);
}
console.log(result);

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