0

I'm a bit curious why the behaviors are different between the two solutions posted below. In the Failing solution, I've concated the zeros array to what I assume by the time of execution, would be the result array of the filter operation. I'm curious why the result is not the updated concated variant (an array with 0s at the end) and instead if simply the initial output of the filter operation.

Passing:

const moveZeros = function (arr) {
 let zeros = [];
 for (let i = 0; i < arr.length; i++) {
   if (arr[i] === 0) zeros.push(0);
 }
 let filteredArray = arr.filter( element => element !== 0).concat(zeros)
 return filteredArray;
  //returns [1,2,3,0,0,0]
}

Failing:

const moveZeros = function (arr) {
 let zeros = [];
 for (let i = 0; i < arr.length; i++) {
   if (arr[i] === 0) zeros.push(0);
 }
 let filteredArray = arr.filter( element => element !== 0);
 // shouldnt the line below concat zeros to the filter result?
 filteredArray.concat(zeros);
 return filteredArray;
  //returns [1,2,3]
}

This also passes: return filteredArray.concat(zeros)

kevin
  • 2,707
  • 4
  • 26
  • 58

3 Answers3

2

concat() doesn't modify the array in place, it returns a new array. Your failing version doesn't return the new array, it returns the original array.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Array.concat() return the concatenated array instead of the original.

let arr = [1,0,0,2,3,0];
let zeros = [];

for (let i = 0; i < arr.length; i++) {
   if (arr[i] === 0) zeros.push(0);
 }

let filteredArray = arr.filter( element => element !== 0);
 
console.log(filteredArray);
 
let concatenatedArray = filteredArray.concat(zeros);
 
console.log(concatenatedArray);

So you need to reassign filteredArray like:

filteredArray = filteredArray.concat(zeros);
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
1

From the MDN Web Docs

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

In your passing solution you are assigning the result of a .concat() to a variable, and then returning that variable, whereas in your failing solution, you are returning the original array, because you did not assign the result of filteredArray.concat(zeros) to anything

Ryan
  • 150
  • 6