0

I want to filter an array of objects with an array attribute based on another array:

[
  {
   id: 50,
   name: 'test1',
   countries: ['RO','GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }, {
    id: 52,
    name: 'test3',
    countries: ['DE'],
  }
]

I want to return an array of objects that can by filtered by an array of countries, meaning if I want to filter by 1, 2 countries.

1. countries: ['RO']

or

2. countries: ['RO', 'DE'],

The expected output would be:

1.

[
  {
   id: 50,
   name: 'test1',
   countries: ['RO', 'DE' ,'GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }
]

2.

[
  {
   id: 50,
   name: 'test1',
   countries: ['RO', 'DE' ,'GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }, {
    id: 52,
    name: 'test3',
    countries: ['DE'],
  }
]
0

2 Answers 2

1

You can use filter() and includes() methods;

var import1 = [
  {
   id: 50,
   name: 'test1',
   countries: ['RO','GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }, {
    id: 52,
    name: 'test3',
    countries: ['DE'],
  }
];

var export1 =  import1.filter(function(importz){
	
return importz.countries.includes("DE");
});

console.log(export1);

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

1 Comment

the includes should expect an array of strings, found out how to filter them: array1.filter(object => object.countries.find(country => arrayOfCountries.includes(country)))
0

Use this function to find multiple values exist in javascript array

var containsAll = arr1.every(function (i) { return arr2.includes(i); });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.