Kenzo_Gilead
Kenzo_Gilead

Reputation: 2439

How to find array in array

I need to find the elements in a first array that match with elements in a second array. For example:

this.languages = [
      {id: 'es', name: 'Español'},
      {id: 'fr', name: 'Frances'},
      {id: 'en', name: 'Ingles'},
      {id: 'pt', name: 'Portugues'}
];

Must return the languages that match win the next array:

this.languagesSelected = [
      'es', 'fr'
];

The result will be:

this.languages = [
      {id: 'es', name: 'Español'},
      {id: 'fr', name: 'Frances'}
];

Tryng from :

questions.filter(x => x.id === id);
questions.find(x => x.id === id);

I cant compare the second array.

Thanks mates

Upvotes: 0

Views: 74

Answers (4)

Sara
Sara

Reputation: 751

You have a good start using filter() method, but your condition is not good. You need to check if any of the languages in selectedLanguages array exists in languages list. So here some() method will help.

The some() method tests whether at least one element in the array passes the test

let languages = [
      {id: 'es', name: 'Español'},
      {id: 'fr', name: 'Frances'},
      {id: 'en', name: 'Ingles'},
      {id: 'pt', name: 'Portugues'}
];

let languagesSelected = [
      'es', 'fr'
];

let result = languages.filter(e => languagesSelected.some(element => e.id == element));

console.log(result);

Another method you can use is includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

let languages = [
      {id: 'es', name: 'Español'},
      {id: 'fr', name: 'Frances'},
      {id: 'en', name: 'Ingles'},
      {id: 'pt', name: 'Portugues'}
];

let languagesSelected = [
      'es', 'fr'
];

let result = languages.filter(e => languagesSelected.includes(e.id));;

console.log(result);

Upvotes: 1

Nick Parsons
Nick Parsons

Reputation: 50674

This can be done efficiently by creating a Map of id: object pairs from your languages array, which you can use while you .map() over your languagesSelected array:

const languages = [ {id: 'es', name: 'Español'}, {id: 'fr', name: 'Frances'}, {id: 'en', name: 'Ingles'}, {id: 'pt', name: 'Portugues'} ];
const languagesSelected = ['es', 'fr'];

const lut = new Map(languages.map((o) => [o.id, o]));
const res = languagesSelected.map(k => lut.get(k));
console.log(res);

This will be O(N + K) vs the O(NK) you would get with a filter/includes/indexOf/some methods

Upvotes: 2

Chrillewoodz
Chrillewoodz

Reputation: 28328

Try this:

const result = this.languages.filter(lang => this.languagesSelected.includes(lang.id));

Upvotes: 1

Lotte Lemmens
Lotte Lemmens

Reputation: 581

languages.filter(l=>this.languagesSelected.indexOf(l.id)>-1);

Upvotes: 1

Related Questions