1

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?

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks buddy!! I want to do more practice on these basic things. I need some questions to build logic on managing the array in Javascript. Any useful link would be better.
You are most welcome. As far as I know there is no such site you can get the logic help, you can master the array built-in functions which will help to implement any array manipulations:)
one more question If I want to store the returned array in another array say array3 then how could I achieve that?
Actually, it showing me this Array [1,2,3,4,6,7] when I take let array3=[].
1

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);

1 Comment

Thanks buddy!! I'll try with this too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.