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

121
Visualizações
How to rearrange array in place using loop

I have this array [-1, 8, -1, 6, -1, 4, -1, 2, 0, -1]

I want to rearrange in place using the loop, where the element will place in its index

For example, element 8 will be placed in the 8th index, element 0 will be in the 0th index

output [0,-1,2,-1,4,-1,6,-1,8,-1];

This is my code

let arr = [-1, 8, -1, 6, -1, 4, -1, 2, 0, -1];

for (let i = 0; i < arr.length; i++) {
  const elem = arr[i];
  // console.log('---',elem)
  if (i !== arr[i]) {
    if (arr[i] !== -1) {

      const valInd = arr[arr[i]];
      arr[arr[i]] = elem;
      arr[i] = valInd
    }
  }

};

console.log(arr);

Please help me understand where I am missing

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

0

You forgot to sort an array. First sort it and then use your logic

let arr = [-1, 8, -1, 6, -1, 4, -1, 2, 0, -1];
arr.sort()
for (let i = 0; i < arr.length; i++) {
  const elem = arr[i];
  // console.log('---',elem)
  if (i !== arr[i]) {
    if (arr[i] !== -1) {

      const valInd = arr[arr[i]];
      arr[arr[i]] = elem;
      arr[i] = valInd
    }
  }

};

console.log(arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

let arr = [-1, 8, -1, 6, -1, 4, -1, 2, 0, -1];
let output = new Array(arr.length).fill(-1);

arr.forEach(el => {
  if(el === -1) return;
  output[el]= el;
});
console.log(output);

about 4 years ago · Juan Pablo Isaza Relatório

0

I think this code will help you, if you want only run for this items.

let arr = [-1, 8, -1, 6, -1, 4, -1, 2, 0, -1];
for (let i = 0; i < arr.length; i++) {
  if (arr.includes(i)) {
    const ind = arr.indexOf(i);
    arr[ind] = arr[i];
    arr[i] = i;
  }
}
console.log(arr);

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