-1

This is a function that takes a nested array and element, it then goes through the array and whenever it finds the element in a sub array, that sub array must be deleted so that the returned array is all the sub arrays that doesn't have that element within.

Here is my code:

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){
         arr[i].splice(0,arr[i].length);
       }
      }
    }
    for(let i=0; i<arr.length;i++){
      if(arr[i]!=""){
       newArr[i]=[...arr[i]];
      }  
   }
  return newArr;
}

it works perfectly when I test it with these arguments:

filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)
filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")
filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)

But when I test it with this: filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2) it returns [ , [ 'flutes', 4 ] ] Does that mean that my conditional statement failed to delete the empty element that I get in the result? If so, why?

  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Aug 04 '22 at 11:37

1 Answers1

0

I did not take the time to look into this particular issue. But you can write this code much condenser.

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

console.log(filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2))

What this code does is only include the subArrays that do not include the elem value.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43