Reputation: 6049
I have just started learning the array methods in javascript. I want to delete elements in an array based on another array. I tried with the below approach but didn't get the expected result.
const array1 = [1, 2, 3, 4, 5, 6, 7];
const array2 = [2, 4, 5];
array2.forEach(a2 => {
array1.filter(a1 => a1 !== a2)
})
console.log(array1);
// actual output: Array [1,2,3,4,5,6,7];
// expected output: Array [1,3,6,7]
Which would be the best array method suited here?
Upvotes: 1
Views: 84
Reputation: 68933
Array.prototype.filter()
returns a new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.
You have to reassign the returned value to the array. Please note, you can not reassign a const variable, use var or let instead.
let array1 = [1, 2, 3, 4, 5, 6, 7];
const array2 = [2, 4, 5];
array2.forEach(a2 => {
array1 = array1.filter(a1 => a1 !== a2);
})
console.log(array1);
Update: There are some issues in the approach you are trying to achieve the result. There is no need to use forEach()
here at all, you can simply use filter()
and in each iteration check if the current item is not exists in array2 using includes()
like the following way:
let array1 = [1, 2, 3, 4, 5, 6, 7];
const array2 = [2, 4, 5];
const array3 = array1.filter(a1 => !array2.includes(a1));
console.log(array3);
Upvotes: 1
Reputation: 1091
ARRAY.filter
do not mutate the array. If possible, declare array1
with let
so that you can reassign it. (Just like the other answer)
By the way, you can use ARRAY.includes(ELEMENT)
to check whether ELEMENT
is in ARRAY
. So you can simplify the code to:
let array1 = [1, 2, 3, 4, 5, 6, 7];
const array2 = [2, 4, 5];
array1 = array1.filter(a1 => !array2.includes(a1));
console.log(array1);
or
const array2 = [2, 4, 5];
const array1 = [1, 2, 3, 4, 5, 6, 7].filter(a1 => !array2.includes(a1));
console.log(array1);
Upvotes: 1