Home > OS >  filter an array based on values of another array in typescript
filter an array based on values of another array in typescript

Time:12-20

if I have an array looking as the following:

names: [{
  value: 'recordedData',
  desc: 'Data'
} {
  value: 'recordedNumbers',
  desc: 'numbers'
} {
  value: 'recordedNames',
  desc: 'names'
}]

and another array looking as the following:

displayed: [{
  value: 'data',
  desc: 'Data'
} {
  value: 'numbers',
  desc: 'numbers'
}]

I want to filter the first array based on the second array so I would have the following resulted array :

DisplayedNames: [{
  value: 'recordedData',
  desc: 'Data'
} {
  value: 'recordedNumbers',
  desc: 'numbers'
}]

CodePudding user response:

Using Array.prototype.filter() and Array.prototype.some() is an elegant way to achieve this

const names = [{value: 'recordedData', desc: 'Data'},
 {value: 'recordedNumbers', desc: 'numbers'},
 {value: 'recordedNames', desc: 'names'}];
 
const displayed = [{
  value: 'data',
  desc: 'Data'
}, {
  value: 'numbers',
  desc: 'numbers'
}]

 const result = names.filter(x => displayed.some(y => y.desc === x.desc));
 
 console.log(result);

More about Array.prototype.some() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some More about Array.prototype.filter() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

  • Related