2

I have two arrays in the code below - which matches is the main one and the other played which serves it is purpose for elements to filter out in the main array:

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = [2,5];

I need to filter out elements in matches based on played array, which means if there is any 2 or 5 in, then remove it altogether. Also the played array can be any length, min is 1.

Expected output should be

[[1,4],[3,1],[3,4]];

So I have tried this piece of code, but it doesn't yield the result I want.

var result = matches.map(x => x.filter(e => played.indexOf(e) < 0))

So anyway to achieve this?

3 Answers 3

1

You could check with some and exclude the unwanted arrays.

var matches = [[1, 4], [3, 1], [5, 2], [3, 4], [4, 5], [2, 1]],
    played = [2, 5],
    result = matches.filter(a => !a.some(v => played.includes(v)));

console.log(result);

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

Comments

1

While filtering, check that .every one of the subarray elements are not included in [2, 5]:

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = [2,5];

const result = matches.filter(
  subarr => played.every(
    num => !subarr.includes(num)
  )
);
console.log(result);

Comments

0

Another way would be to create a Set of played to avoid iterating it again and again:

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = new Set([2,5]);
var out = matches.filter(a => !a.some(num => played.has(num)));
console.info(out)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.