I want to implement a function that takes an array and some other arguments then removes the other arguments from that array.
So i used the rest parameter for the second argument then used Array.from to convert it an array,
then used .length to get its length to use it as the second parameter for splice and it doesn’t works.
I know there are better ways to solve this problem, but I want to why it’s not working .
const removeFromArray = function(array, ...number) {
let numArray = Array.from(number)
for(let i = 0; i < array.length ; i++ ){
if(number == array[i]){
array.splice( i , numArray.length);
}
}
return array;
};
removeFromArray([2, 1, 2, 3, 4], 1, 2);
expecting the output to be: [3, 4]
but it’s: [2, 1, 2, 3, 4]
3
Answers
const removeFromArray = function(array, …numbers) {
let numArray = Array.from(numbers);
};
console.log(removeFromArray([2, 1, 2, 3, 4], 1, 2));
number == array[i]
will never betrue
. Sincenumber
is an Array and you are comparing it with a single number (even ifarray[i]
were an Array, the result would befalse
, since arrays aren’t compared like that, in javascript).If you want to remove values from an Array an easy solution would be to use the
filter
function (link to documenation).As pointed out by winner_joiner, the easier solution in this case is to use the built-in
.filter
method, so this is just provided as a learning exercise.This is a demonstration of why naming variables carefully is so useful, as the bug becomes more obvious if we rename them like this:
(Note that I’ve removed the
Array.from
call, because JavaScript rest parameters are already an array. SonumsToRemove
replaces bothnumber
andnumArray
in the original code.)Two things hopefully now stand out:
if(numsToRemove == targetArray[targetArrayIdx])
is comparing a whole list of numbers to a single item in the target arraytargetArray.splice(targetArrayIdx, numsToRemove.length);
is going to delete as many items as are in thenumsToRemove
list every timeWhat we want instead is:
numsToRemove
, using numsToRemove.includes(value).1
totargetArray.splice
:This leaves a more subtle bug: as we delete items, the remaining items in the array move; so after we delete the
2
at index 0, the1
moves to index 0 – but we carry on with thefor
loop, and don’t check index 0 again.We can avoid this by iterating the loop backwards, instead of forwards:
Now when we remove an item, the only items that move are ones we’ve already checked, so we safely check each item once.