0

I have two arrays of objects:

array1 = [
    {id:1, name: 'one'},
    {id:4, name: 'four'}
]

array2 = [
    {id:1, name: 'one'},
    {id:2, name: 'two'},
    {id:3, name: 'three'},
    {id:5, name: 'five'},
    {id:6, name: 'six'},
    {id:7, name: 'seven'}
]

I would like to remove any object from array1 who's id does not exist in array2.

so my expect result would be:

array1 = [
    {id:1, name:'one'}
]
Joe
  • 4,618
  • 3
  • 28
  • 35

4 Answers4

2

Use lodash's _.intersectionBy():

var array1 = [
    {id:1, name: 'one'},
    {id:4, name: 'four'}
];

array2 = [
    {id:1, name: 'one'},
    {id:2, name: 'two'},
    {id:3, name: 'three'},
    {id:5, name: 'five'},
    {id:6, name: 'six'},
    {id:7, name: 'seven'}
];

var result = _.intersectionBy(array1, array2, 'id');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

A fast and readable option would be:

var referenceKeys = array2.map(function(entity) { return entity.id; });

var result = array1.filter(function(entity) {
    return referenceKeys.indexOf(entity.id) !== -1;
});

But no guarantee that it's the fastest in all dimensions. (Number of repeats, length of array1, length of array2).

K. Rohde
  • 9,439
  • 1
  • 31
  • 51
0

You could use a standard approach by using a hash table which uses just one iteration for both arrays.

var array1 = [{ id: 1, name: 'one' }, { id: 4, name: 'four' }],
    array2 = [{ id: 1, name: 'one' }, { id: 2, name: 'two' }, { id: 3, name: 'three' }, { id: 5, name: 'five' }, { id: 6, name: 'six' }, { id: 7, name: 'seven' }],
    hash = Object.create(null),
    result;

array2.forEach(function (o) {
    hash[o.id] = true;
});

result = array1.filter(function (o) {
    return hash[o.id];
});

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use a Set for this:

const seenIds = array2.reduce((set, o) => set.add(o.id), new Set());
const result = array1.filter(o => seenIds.has(o.id));
Justin Summerlin
  • 4,938
  • 1
  • 16
  • 10
  • `const seenIds = new Set(array2.map(o -> o.id));` Just a little shorter. :) –  Nov 15 '17 at 19:05