Sunny
Sunny

Reputation: 1

I am not getting how to do it for a case when we have to remove elements listed in another array

function removeListedValues(arr) {
                var what, a = arguments, L = a.length, ax;
                while (L > 1 && arr.length) {
                    what = a[--L];
                    while ((ax= arr.indexOf(what)) !== -1) {
                        arr.splice(ax, 1);
                    }
                }
                return arr;
            }

arr: The given array

without: A list of elements which are to be removed from arr. Return the array after removing the listed values.

Input: arr: [1, 2, 2, 3, 1, 2] without: [2, 3]

Output: [1, 1]

Upvotes: 0

Views: 29

Answers (2)

Unmitigated
Unmitigated

Reputation: 89394

You can create a Set (for faster lookup) from the array of values to exclude and use Array#filter along with Set#has.

const arr = [1, 2, 2, 3, 1, 2], without = new Set([2, 3]);
const res = arr.filter(x => !without.has(x));
console.log(res);

Upvotes: 1

Lu Kevin
Lu Kevin

Reputation: 23

To remove something in array, suggest using .filter

const input = [1, 2, 2, 3, 1, 2];
const without = [2, 3];

const result = input.filter(value => !without.includes(value))
console.log(result)

Upvotes: 2

Related Questions