0

I am working on FCC challenges, learning JS. Here is the link of challenge that cofuses me.

I kinda solved it, but one code that should work, while other does not, and I would assume they are essentially the same things.

This is a code that works:

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  return [].concat(arr).sort(function(a, b) {
    return a - b;
  });
  // Add your code above this line
}
nonMutatingSort(globalArray);

And this code does not work

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  let newArr = [];
  newArr.concat(arr);
  return newArr.sort(function(a,b){return a-b;});
  // Add your code above this line
}
nonMutatingSort(globalArray);

My question is essentially why? Both codes concatenate old array to new one, and both functions should return sorted array.

However in first function concatenation fails... it returns only empty arr. Why? I am so confused. It works outside of the function, however not in function.

2 Answers2

1

concat does not mutate any existing array (either the array the function is called on, or the array(s) in the parameter list). When you call concat, you return a new array. So, the standalone statement

newArr.concat(arr);

does not do anything - you concatenated newArr with arr, creating a new combined array, but that combined array is not assigned to anything; it gets evaluated and then discarded.

const arr1 = ['a'];
const arr2 = ['b'];

// Does not do anything by itself:
arr1.concat(arr2);

console.log(arr1);
console.log(arr2);

Assign the result to newArr instead:

newArr = newArr.concat(arr);

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  let newArr = [];
  newArr = newArr.concat(arr);
  return newArr.sort(function(a,b){return a-b;});
  // Add your code above this line
}
console.log(nonMutatingSort(globalArray));
// Original array is not mutated:
console.log(globalArray);

Or, avoid the initial declaration of newArr entirely, and use your original code (which I'd prefer). Actually, to be even more terse, you might just slice the original array, rather than explicitly creating an empty one:

var globalArray = [5, 6, 3, 2, 9];
const nonMutatingSort = arr => arr.slice().sort((a, b) => a - b);
console.log(nonMutatingSort(globalArray));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

concat method return a new array so you need to save in same variable or in another variable. In your case :

var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
  // Add your code below this line
  let newArr = [];
  newArr = newArr.concat(arr); //here it will return new new which you need to save
  return newArr.sort(function(a,b){return a-b;});
  // Add your code above this line
}
nonMutatingSort(globalArray);
Shubham Verma
  • 4,918
  • 1
  • 9
  • 22