Joe
Joe

Reputation: 4738

Using Lodash or vanilla JS what is the most efficient way to filter an array based on object keys?

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'}
]

Upvotes: 0

Views: 870

Answers (4)

Ori Drori
Ori Drori

Reputation: 192477

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>

Upvotes: 2

Justin Summerlin
Justin Summerlin

Reputation: 5096

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386736

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

Upvotes: 0

K. Rohde
K. Rohde

Reputation: 9686

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

Upvotes: 1

Related Questions