Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading