DEV Community

loading...

Iterating Through All an Array's Items Using For Loops

rthefounding profile image Randy Rivera ・1 min read
  • Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. The technique which is most flexible and offers us the greatest amount of control is a simple for loop.
  • Ex: I 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. Let's 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.
function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line

  // Only change code above this line
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function filteredArray(arr, elem) {
  let newArr = [];

for (let i = 0; i < arr.length; i++) {
  let outer = arr[i];
  if (outer.indexOf(elem) === -1) { 
     //Checks every parameter for the element and if is NOT there continues the code
    newArr.push(outer); //Inserts the element of the array in the new filtered array
  }
}
  return newArr;
}
Enter fullscreen mode Exit fullscreen mode
console.log(filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)); will display [[10, 8, 3], [14, 6, 23]]
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app