Why does this function mutate data?

111 views Asked by At
function bubbleSort(toSort) {
  let sort = toSort;
  let swapped = true;
  while(swapped) {
    swapped = false;
    for(let i = 0; i < sort.length; i++) {
      if(sort[i-1] > sort[i]) {
        let temp = sort[i-1];
        sort[i-1] = sort[i];
        sort[i] = temp;
        swapped = true;
      }
    }
  }
  return sort;
}

let asdf = [1,4,3,2];
let asd = bubbleSort(asdf);

console.log(asdf, asd);

The output to this code is: [ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ].

What I would expect:         [ 1, 4, 3, 2 ] [ 1, 2, 3, 4 ].

What I'm wondering, is why does this mutate the asdf variable? The bubbleSort function takes the given array (asdf), makes a copy of it (sort), and then deals with that variable and returns it, which asd is set equal to. I feel like an idiot but I have no clue why this is :(

3

There are 3 answers

0
Paul On BEST ANSWER

The bubbleSort function takes the given array (asdf), makes a copy of it (sort)

No, it doesn't. Assignment doesn't make a copy of an object, it creates another reference to an existing object.

A simple way to copy an array is to use Array.prototype.slice:

  let sort = toSort.slice( 0 );

For more on copying objects in general see: How do I correctly clone a JavaScript object?

0
Jaxon On

You are sorting the input list given as a function argument which is mutable. When you assign the list to a new variable, it doesn't create a 'copy' it just creates another reference pointing to the same list, same data, which you then go ahead a sort. This is why both asdf and add variables are the same, because they are two variables that point to the same memory location, same data.

If you wish to copy the array so not to modify the input array, have a look into the javascript slice() method.

0
vijay On

You need to clone the original array to avoid the change happening in original array. clone can be done by using

  1. slice() prototype method.
  2. loop.
  3. Array.from().
  4. concat().

Replace let sort = toSort; with let sort = toSort.slice(0); or

 let sort=[];
  for(var i=0;i < toSort.length;i++){
  sort[i]=toSort[i];  
  }

or

  let sort = Array.from(toSort);

or

let sort = toSort.concat();

function bubbleSort(toSort) {
  let sort = toSort.slice(0);
  let swapped = true;
  while (swapped) {
    swapped = false;
    for (let i = 0; i < sort.length; i++) {
      if (sort[i - 1] > sort[i]) {
        let temp = sort[i - 1];
        sort[i - 1] = sort[i];
        sort[i] = temp;
        swapped = true;
      }
    }
  }
  return sort;
}

let asdf = [1, 4, 3, 2];

let asd = bubbleSort(asdf);

console.log(asdf, asd);