Developer
Developer

Reputation: 1040

Typescript remove values from array if it doesn't exist in multidimensional array

I have a single dimensional and an array of Objects

array1 = [1, 3, 15, 16, 18];

array2 = [
       { id: 1, dinner : pizza },
       { id: 15, dinner : sushi },
       { id: 18, dinner : hummus }
]

I'm trying to remove values from array1 that are not in array2 based on the id.

I know how to remove in two single dimensional arrays but I'm unable to modify the code to remove when array2 is an array of Objects.

const array1 = array1.filter(id => array2.includes(id));

Any help would be appreciated.

Upvotes: 1

Views: 157

Answers (2)

ABGR
ABGR

Reputation: 5205

You can map all Ids and then filter

var array1 = [1, 3, 15, 16, 18];

var array2 = [
       { id: 1, dinner : "pizza" },
       { id: 15, dinner : "sushi" },
       { id: 18, dinner : "hummus" }
]

  const Ids = array2.map(i=> i.id);
  var res = array2.filter(i => Ids.includes(i.id)); 
  var res2 = Ids.filter(i => array1.includes(i))// Or, just to get common Ids
  
  console.log(res)
   console.log(res2)

But I suggest you should use reduce to avoid two passes:

var array1 = [1, 3, 15, 16, 18];

var array2 = [
       { id: 1, dinner : "pizza" },
       { id: 15, dinner : "sushi" },
       { id: 18, dinner : "hummus" }
]

var res = array2.reduce((acc, {id})=>{
  if(array1.includes(id)){
   acc = [...acc, id]
  }
  return acc
},[]);

console.log(res)

Upvotes: 0

Yousaf
Yousaf

Reputation: 29282

Both arrays are single dimension arrays.

use .some() function along with .filter() function to remove those numbers from array1 which are not present as id in any of the objects in array2

const array1 = [1, 3, 15, 16, 18];
const array2 = [
    { id: 1, dinner : 'pizza' },
    { id: 15, dinner : 'sushi' },
    { id: 18, dinner : 'hummus' }
]

const filteredArr = array1.filter(v => array2.some(o => v == o.id));

console.log(filteredArr);

Upvotes: 1

Related Questions