Iterate Through All an Arrays Items Using For Loops

Iterate Through All an Arrays Items Using For Loops
0.0 0

#1

Hey actually i have completed this challenge but i want to know that if there is more efficient way to write this code .

Here is my code.


function filteredArray(arr, elem) {
 let newArr = [],row=[],item=true;
  for (let i = 0; i < arr.length; i++) {
    item=true;
    row=[];
  for (let j = 0; j < arr[i].length; j++) {
  if(arr[i][j]==elem)
    {
      item=false;
      break;
    }
    else{
      row.push(arr[i][j]);
      item=true;
    }
  }
    if(item)
      newArr.push(row);
    }
 
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.clear();
console.log(filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18));

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

function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let index in arr) {
if((arr[index].indexOf(elem) == -1)) {
newArr.push(arr[index])
}
}
// change code above this line
return newArr;
}


#3

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#4

thanks :slight_smile:


#5

thanks man <3 this is awesome. will try to improve my code.


#6

Well, this passes:

function filteredArray(arr, elem) {
  let newArr = []
  for (let i=0; i<arr.length; i++) {
    if (!arr[i].includes(elem))
      newArr.push(arr[i])
  }
  // change code above this line
  return newArr;
}

But I think this is a more “modern” approach:

const filteredArray = (arr, elem) => arr.filter(a => !a.includes(elem))

but it will fail the test because you are required to use a for loop.


#7

awesome you just did this in one line … :heart_eyes: thanks


#8

[spoiler]```
function filteredArray(arr, elem) {
let newArr = [];
newArr=[…arr];
for(let i=0;i<newArr.length;i++){
if(newArr[i].indexOf(elem)!=-1){
newArr.splice(i,1);
–i;
}

}
return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));