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'],
  }
]
Eduard
  • 133
  • 6

2 Answers2

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);
novruzrhmv
  • 639
  • 5
  • 13
  • the includes should expect an array of strings, found out how to filter them: array1.filter(object => object.countries.find(country => arrayOfCountries.includes(country))) – Eduard Oct 08 '19 at 11:59
0

Use this function to find multiple values exist in javascript array

var containsAll = arr1.every(function (i) { return arr2.includes(i); });
chans
  • 5,104
  • 16
  • 43