I am still a newbie in programming, and I decided to take up The Odin Project course. I decided to make my own code and see if it works, but so far, I am having errors with this specific problem.
Here is the code I made by myself.
const removeFromArray = function(array,...toDelete) {
const newArray=[];
array.forEach(item=>{
if(item != toDelete){
newArray.push(item);
}
})
return newArray; };
// Do not edit below this line
module.exports = removeFromArray;
And this is the test case I am currently running it by. My code passes the first test case but it fails in the second. Can someone help me understand why? I am pretty sure it has something to do with my if statement but I don't entirely understand why it does not work.
describe('removeFromArray', () => {
test('removes a single value', () => {
expect(removeFromArray([1, 2, 3, 4], 3)).toEqual([1, 2, 4]);
});
test('removes multiple values', () => {
expect(removeFromArray([1, 2, 3, 4], 3, 2)).toEqual([1, 4]);
});
});
The problem is this
item != toDelete
toDelete is an array and you are comparing it with a number
you should search for item inside toDelete instead
!toDelete.includes(item)
The reason why it works with the first example is because, in javascript, 4 == [4] returns true. Your code would not have worked at all if you used === instead of ==.