-1

so for example if i do removeFromArray([1, 2, 3, 4], 2, 3) it should return [1, 4] right now the index variable is only showing the index of the first argument of remove

function removeFromArray(arr, ...remove) {
    let index = arr.indexOf(...remove);
    let amountRemove = arguments.length - 1;

    arr.splice(index, amountRemove);



    return arr;
}
kyopa
  • 11
  • 1
  • indexOf is what to look for and start index. Not sure what you are expecting from `indexOf(2, 3);` – epascarello Jan 28 '22 at 19:11
  • You are going to have to use filter or you have to loop over each number in remove and get their indexes. There is no built in code that will get you all the indexes – epascarello Jan 28 '22 at 19:13
  • so i should do ```for (const number of ...remove)``` ??? – kyopa Jan 28 '22 at 19:18
  • https://stackoverflow.com/questions/19957348/remove-all-elements-contained-in-another-array – epascarello Jan 28 '22 at 19:18
  • is there a chance that a number occurs multiple times in arr? like `removeFromArray([1, 2, 3, 2, 4, 2], 2, 3)` and how do you want to handle that? Do you want to remove only the first occurrence or all? And what would be the expected output? – Thomas Jan 28 '22 at 19:19
  • dont worry about that it wasnt asked in the exercise – kyopa Jan 28 '22 at 19:21

2 Answers2

0

Hi,

First: indexOf method work only with one parameter. Consecutive it result -1

Second: amountRemove variable that you are using to delete mean that it must you want delete from the array is consecutive and not separated and this is not good experience.

Simply to solve this problem using loop or forEach or any method make loop on the values of the array

and his your code fixed

function removeFromArray(arr, ...remove) {
    remove.forEach(element => {
        let index = arr.indexOf(element);
        arr.splice(index, 1);
    })
    return arr;
}
Philo
  • 428
  • 4
  • 11
0

You looking for something like that?

function removeFromArray(arr, ...remove) {    
    let temp = []
    arr.forEach(n => {
      if (!remove.includes(n) ) {        
        temp.push(n) 
      }
    });
    return temp;
}

console.log('res',removeFromArray([1, 2, 3, 4], 2, 3) )
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79