1

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.

3
  • What do you mean by "multidimensional"? Both arrays have single dimension in above example Commented Jun 19, 2020 at 11:12
  • array1.filter( i => (array2.map(o => o.id)).includes(i)) Commented Jun 19, 2020 at 11:18
  • reduce would perform better to avoid two passes. Elaborating below: Commented Jun 19, 2020 at 11:24

2 Answers 2

1

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);

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.