Reputation: 1444
let masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
let selectedList=[2,3];
The desired result is to have
//desiredList=[{id:2,name:'Def'},{id:3,name:'Ghi'}]
Currently what I am doing is
let parsedArray = [];
masterList.forEach(mItem => {
selectedList.forEach(sItem => {
if (mItem.id === sItem) {
parsedArray.push(mItem);
}
});
});
desiredList=parsedArray
I do not find this method efficient when iterating over large arrays, is there any logic, any inbuilt javascript operators using which I can achieve the same?
Upvotes: 1
Views: 7741
Reputation: 370689
Turn the first array into an object indexed by id
first, so you can look up the appropriate matching object in O(1)
time, and then you can .map
the selectedList
:
const masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
const selectedList=[2,3,4];
const masterById = masterList.reduce((a, obj) => {
a[obj.id] = obj;
return a;
}, {});
const desiredList = selectedList.map(id => masterById[id]).filter(Boolean);
console.log(desiredList);
Upvotes: 2
Reputation: 386560
You could take a map
with id
as key and the object as value and map the wanted values from the map by mapping selectedList
.
This approach uses the order from selectedList
.
var masterList = [{ id: 1, name: 'Abc' }, { id: 2, name: 'Def' }, { id: 3, name: 'Ghi' }],
selectedList = [2, 3],
result = selectedList.map(Map.prototype.get, new Map(masterList.map(o => [o.id, o])));
console.log(result);
Upvotes: 6
Reputation: 4806
Try this:
let masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
let selectedList=[2,3];
const result = masterList.filter(({id})=> selectedList.includes(id));
console.log(result);
Upvotes: 2
Reputation: 11975
You can use Array filter()
to do this.
Demo:
let masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
let selectedList=[2,3];
let desiredList = masterList.filter((val) => selectedList.includes(val.id));
console.log(desiredList)
Upvotes: 4
Reputation: 36564
You can first convert selectedList
to Set
and then use filter()
method array of objects.
You can use Set.prototype.has
to check whether the id
of the objects exists in the set or not. And this method has O(1) time-complexity. So the time-complexity of the whole algorithm will be linear.
let masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
let selectedList = [2,3];
let set = new Set(selectedList);
let res = masterList.filter(x => set.has(x.id));
console.log(res)
Upvotes: 3
Reputation: 67296
It should be a simple filter
on the masterList
:
masterList.filter(item => selectedList.includes(item.id));
Upvotes: 4