Find and delete elements in nested arrays by using for loops (JAVASCRIPT)

Find and delete elements in nested arrays by using for loops (JAVASCRIPT)
0.0 0

#1

Tell us what’s happening:
My thought process making this code: I nested a for loop inside a for loop to look through the nested array. If the elem is an element of a nested array, the whole nested array is deleted. Note that I set the newArray to copy the arr, so I could delete the nested arrays directly.

When I try to run the code I get the error message: “Cannot read property ‘1’ of undefined”.

I have checked the code for any spelling mistakes, misplaced curly brackets or parenthesis, but I could not find any errors. Is the delete newArr[i]; a valid line of code? Would that delete the whole array, or would it just “clear” it, so it would be like this []?

I would appreciate it if you could give an explanation as to why this does not work, and how to fix it.
*Your code so far


function filteredArray(arr, elem) {
  var newArr = [];
  // change code below this line
  newArr = [...arr];
for (var i = 0; i < arr.length; i++){
  for(var x = 0; x < arr[i].length; x++){
    if (elem == newArr[i][x]){
      delete newArr[i];
    }
  }
}
  // change code above this line
  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));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops


#2

Hi Mikael

The delete keyword is for removing properties on objects, not array elements or variables. You could simply replace you delete statement with newArr[i] = [] to clear the array, then filter out all empty arrays in your return statement.

function filteredArray(arr, elem) {
  var newArr = [];
  // change code below this line
  newArr = [...arr];
  for (var i = 0; i < arr.length; i++){
    for(var x = 0; x < arr[i].length; x++){
      if (elem === newArr[i][x]){
        newArr[i] = [];
      }
    }
  }
  // change code above this line
  return newArr.filter(function(i){ return i.length > 0 });
}

But I would strongly suggest that you make this code more simple by letting the array prototype functions help you. You will thank yourself when revisiting this code later. The array prototype has many functions (like filter and includes) that can make your code a lot more readable.

function filteredArray(arr, elem) {
	// array.filter(fn) should remove all elements
	// where fn returns false 
	return arr.filter(function(item){
  		// keep items that does not include elem
  		return !item.includes(elem);
  	});
}

#3

Ah, thank you for the solution. I have just finished the Basic Javascript Course and read that it was recommended to take the Basic Data Structures first, so far I have not come across the array prototype functions, but they made the solution much simpler.

Not sure if I should go through the javascript course step by step, I found the ES6 challenges very hard to understand.

EDIT: I tried the first solution, but got the error: newArr is not defined. The newArr is declared on line 2 with var newArr = [];


#4

No problem. It is probably a good idea to do it the hard way first so that you get an understanding of what’s happening under the hood of those functions anyway. What you also could try to do is flip the problem around and not copy the whole array and then remove the unwanted items, but rather assign and empty array to newArr and then push the wanted items in you loop. You would have to exit the inner for-loop early though so that you won’t end up with duplicates where there are multiple matches (e.g. [3,2,3]). Early break out of loops can be done with the keyword break.

EDIT: If you are interested I’ve created a simple implementation of the filter and includes. See how flexible the code becomes when the evaluation function is passed in as an argument? You could reuse the filter implementation to fit other needs without rewriting or duplicating code :slight_smile: NB it’s generally not a good idea to extend the prototype of native javascript types as I’ve done here, this is just for demonstration.