I am trying to be better in js and I stuck while trying to solve this problem,
"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."
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
for (let j=0;j<arr.length;j++){
newArr.push(arr[j])
}
for(let i=0; i<newArr.length; i++){
for (let k=0; k<newArr[i].length; k++){
if (newArr[i][k] === elem){
newArr.splice(i,1)
}
}
}
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
The code above is what I have write by far. And I am getting an error;
for (let k=0; k<newArr[i].length; k++){
TypeError: Cannot read properties of undefined (reading ‘length’)
"
Can you guys help me, how can I fix the code?
Edit: Code should return []
4
Answers
newArr.splice(i,1) here you are modyfing original array . and you need to modify nested array . try this -> newArr[i].splice(k,1)
Here I am iterating over the
newArr
array in reverse order, and iterating over the nested arrays in reverse order as well. This ensures that removing elements from the array using the splice method will not cause the loop to skip over elements or access undefined values.You should be looking to take advantage of functions provided by the JavaScript interpreter and high level functions where possible. There are many such functions that operate on collections such as Arrays.
One such function: Array.prototype.filter.
Filter on two conditions:
arr
is an Array (i.e. Array.prototype.isArray)elem
(i.e. Array.prototype.includes – this answer assumeselem
is a primitive (see note below))Note: Array.prototype.includes tests using equality and Objects are references so their "value" is not equal to a primitive’s value. example:
Array.prototype.splice
function, you MUST loop in the backward direction.