Iterate Through All an Arrays Items Using For Loops

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/

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;
}

2 Likes

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.

markdown_Forums

1 Like

thanks :slight_smile:

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

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.

1 Like

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

[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));

1 Like

You can do it simply using indexOf from the previous challenges:

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