The problem is as follows :
We have defined a function, filteredArray, which takes arr, a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr. Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed.
The problem I am having with my code :
In my solution specifically , I don’t understand why the code only works as expected if the nested loop starts with the number 3 . If that number’s position is changed -as in the 2nd and 4th nested arrays- the function doesn’t work as expected .
function filteredArray(arr, elem) {
let newArr = [];
let myNestedArray;
// Only change code below this line
for (let i = 0; i < arr.length; i++) {
myNestedArray = arr[i];
for (let j = 0; j < myNestedArray.length; j++) {
if (myNestedArray[j] === elem) {
console.log(`Main arr is => ${arr}`);
console.log(`Nested array is => [${myNestedArray}]`);
console.log(`Elem is => ${elem}`);
arr.splice(arr.indexOf(myNestedArray), 1);
myNestedArray = [];
console.log(`#######`);
}
}
}
newArr.push(arr);
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
3
Answers
isValueFoundInSubArray
Code :
When you remove a house from the presentation, what happens is that the circle does not go to the last house that you are considering and as a result, the work that you are considering cannot be done.
It is better to use foreach
Here is an example of removing the data from a nested array in JavaScript by using the Splice method which will help by knowing the index of the nested element.
Code: