Skip to content Skip to sidebar Skip to footer

Why Does This Function Mutate Data?

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] &g

Solution 1:

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:

letsort = toSort.slice( 0 );

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

Solution 2:

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.

Solution 3:

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

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

or

letsort = Array.from(toSort);

or

letsort = toSort.concat();

functionbubbleSort(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);

Post a Comment for "Why Does This Function Mutate Data?"