Home > Net >  function that takes a nested array and element as an argument, return a new array, if a nested array
function that takes a nested array and element as an argument, return a new array, if a nested array

Time:09-24

function filteredArray(arr, elem) {
  let newArr = [];
  for (let i = 0; i < arr.length; i  ) {
    for (let j = 0; j < arr[i].length; i  ) {
      if (arr[i][j] != elem) {
        newArr.push(arr[i]);
      }
    }
  }
  return newArr;
}

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

How should I remove that error? If a nested array doesn't contain element it will push it to newArr.

CodePudding user response:

  1. You need to increment j in that inner loop.

  2. You also need to find a way to check to see if elem has been found, and only if it's been found, to add the nested array to the output.

function filteredArray(arr, elem) {
  let newArr = [];
  for (let i = 0; i < arr.length; i  ) {
    let found = false;
    for (let j = 0; j < arr[i].length; j  ) {
      if (arr[i][j] === elem) {
        found = true;
      }
    }
    if (!found) newArr.push(arr[i]);
  }
  return newArr;
}

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

A more modern method would be to filter out the arrays that where elem is not included:

function filteredArray(arr, elem) {
  return arr.filter(inner => {
    return !inner.includes(elem);
  });
}

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

CodePudding user response:

function filteredArray(arr, elem) {
    let newArr = [];
    for (let i = 0; i < arr.length; i  ) {
        for (let j = 0; j < arr[i].length; j  ) {
            if (arr[i][j] == elem) {
                newArr.push(arr[i]);
            }
        }
    }
    return newArr;
}

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