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'}
]
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>
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).
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);
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.