My exercise is creating a function that takes two parameters: a multi-dimensional array, and a value. I have to return a new array in which all the sub-array that contain the value is removed. My idea is using nesting for loop to search for the value in every sub-array. If the matching is found, remove the sub-array and end the inner loop. But the code was not runing well and I found a problem as below when debugging:
//Assingment is from FreeCodeCamp
function filteredArray(arr, elem) {
let newArr = [];
//my solution start here
newArr = arr;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
//debugging
console.log( "i", i);
console.log( 'j', j);
console.log(arr);
console.log(arr[i]);
console.log(arr[i][j]);
//end debugging
if (arr[i][j] == elem) {
newArr.shift(); //remove the sub-array
j = arr[i].length; //end the inner loop
}
console.log('newArr',newArr);
}
}
//my solution end here
return newArr;
}
// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
The result is:
"i" 0
"j" 0
[[3,2,3],[1,6,3],[3,13,26],[19,3,9]]
[3,2,3]
3
"newArr" [[1,6,3],[3,13,26],[19,3,9]]
"i" 1
"j" 0
[[1,6,3],[3,13,26],[19,3,9]]
[3,13,26]
3
"newArr" [[3,13,26],[19,3,9]]
[[3,13,26],[19,3,9]]
The code was run well in the first i = 0 loop. But in the next loop, i = 1, the parameter array is changed. I supposed it to be the input array of the function but turn out, the first sub-array is removed even though I didn't make any change in that array. Can anyone help me explain this?