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

223
Visualizações
How to insert an array to another array at each iteration of a for loop in javascript

I have a function to bubble sort and I want to save the array after each swap into another array. The bubble sort is working properly and I can log the array after each swap to the console. But I cant seem to push to the other array properly.

Here's my code :

var arr = [5, 4, 3, 2, 1];
var steps = [];

function bubbleSort() {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
      }
      var temp = arr;
      console.log(temp);
      steps.push(temp);
    }
  }
  console.log(steps);
}

const swap = (a, x, y) => {
  var temp = a[x];
  a[x] = a[y];
  a[y] = temp;
};

bubbleSort();

Here's a screenshot of the console :

screenshot of console

It's only when I try to use get a hold of the array at each step that it isn't showing properly? what do I do?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I think clonning the array could work ? var temp = [...arr];

var arr = [5, 4, 3, 2, 1];
var steps = [];

function bubbleSort() {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
      }
      var temp = [...arr];
      console.log(temp);
      steps.push(temp);
    }
  }
  console.log(steps);
}

const swap = (a, x, y) => {
  var temp = a[x];
  a[x] = a[y];
  a[y] = temp;
};

bubbleSort();

about 4 years ago · Santiago Trujillo Relatório

0

You are inserting the Reference of the Temp-Array and not the actual content. This way, you store multiple times the reference and at the End you are presented with all those reference pointing to the last version of your temp Array.

You can use the destructuring assignment of an array, to create an easy shallow copy to be stored.

var arr = [5, 4, 3, 2, 1];
var steps = [];

function bubbleSort() {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1);
      }
      var temp = arr;
      console.log(temp);
      // Changed to destructuring assignment
      steps.push([...temp])
    }
  }
  console.log(steps);
}

const swap = (a, x, y) => {
  var temp = a[x];
  a[x] = a[y];
  a[y] = temp;
};

bubbleSort();

about 4 years ago · Santiago Trujillo 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