BUG: Functional Programming: Return a Sorted Array Without Changing the Original Array

const globalArray = [5, 6, 3, 2, 9];

function nonMutatingSort(arr) {
  // Only change code below this line
let newArr = globalArray.concat();
console.log(newArr);
newArr = newArr.sort(function(a, b){
  return a-b;
});
console.log(newArr);
return newArr;

  // Only change code above this line
}

nonMutatingSort(globalArray);

This code should work. I tried it in JS Fiddle and it works there. I think there is a bug.

JS Fiddle:

const globalArray = [1, 30, 4, 21, 100000];

function nonMutatingSort(arr) {
  // Only change code below this line
let newArr = globalArray.concat();
console.log(newArr);
newArr = newArr.sort(function(a, b){
  return a-b;
});
console.log(newArr);
return newArr;

  // Only change code above this line
}

console.log(nonMutatingSort(globalArray));
console.log(nonMutatingSort([1, 30, 4, 21, 100000]))
Result:

console.log(newArr);
7
newArr = newArr.sort(function(a, b){
8
  return a-b;
9
});
10
console.log(newArr);
11
return newArr;
12
​
13
  // Only change code above this line
14
}
15
​
16
console.log(nonMutatingSort(globalArray));
17
console.log(nonMutatingSort([1, 30, 4, 21, 100000]))
CSS
Tidy
1
​

578px
Console (beta)
Clear console
Minimize
6
0
0
0
☁️ "Running fiddle"

[1, 30, 4, 21, 100000]
[1, 4, 21, 30, 100000]
[1, 4, 21, 30, 100000]
[1, 30, 4, 21, 100000]
[1, 4, 21, 30, 100000]
[1, 4, 21, 30, 100000]

All tests are passed except the last 2:

nonMutatingSort([1, 30, 4, 21, 100000]) should return [1, 4, 21, 30, 100000] .

nonMutatingSort([140000, 104, 99]) should return [99, 104, 140000] .

But it works fine in JS Fiddle.

The bug is that you are hard-coding that your function will only use the globalArray and will ignore the function input arr.

Ah, I see. Changing globalArray to arr fixed it.

1 Like