You can convert your first array of users to a Map
. A Map is similar to an object, however, it has some differences (I'm using a Map here as it's easier to construct from an array compared to an object).
The Map would have the following shape:
Map {
"abc": { key: 'abc', name: 'Anna', age: 22, gender: 'F' },
"def": { key: 'def', name: 'John', age: 25, gender: 'M' },
"ghi": { key: 'ghi', name: 'Mary', age: 27, gender: 'F' },
"jkl": { key: 'jkl', name: 'Joe', age: 30, gender: 'M' }
}
In the code below, the above Map is stored in a variable called lut
(short for look-up-table). Doing lut.get("def")
will return the object stored at the key "def"
, in this case that object is:
{ key: 'def', name: 'John', age: 25, gender: 'M' }
JavaScript engines have optimized this look-up to be incredibly efficient, so creating a Map like this can help improve the overall scalability, meaning it will be efficient if you have many users.
Since order matters in your output, you can use .map()
on your filter
array (which determines the order) to convert each object with the name property to the object in the Map we built. To perform the "conversion" you can return the new object you want, which you can obtain from your Map using .get(o.key)
.
See working example below:
const users = [{ key: 'abc', name: 'Anna', age: 22, gender: 'F' }, { key: 'def', name: 'John', age: 25, gender: 'M' }, { key: 'ghi', name: 'Mary', age: 27, gender: 'F' }, { key: 'jkl', name: 'Joe', age: 30, gender: 'M' }];
const filter = [{ key: 'jkl' }, { key: 'def' }, { key: 'abc' }];
const expected_result = [{ key: 'jkl', name: 'Joe', age: 30, gender: 'M' }, { key: 'def', name: 'John', age: 25, gender: 'M' }, { key: 'abc', name: 'Anna', age: 22, gender: 'F' }];
const lut = new Map(users.map(o => [o.key, o]));
const result = filter.map(f => lut.get(f.key));
console.log(result);
If one of your objects in the filter can have a key for a user which isn't in the users list, the above approach will transform that filter object into "undefined". If you want to ignore it, you can use .filter()
before you map. Using .filter()
will remove all filter objects which don't have a key within the map:
const users = [{ key: 'abc', name: 'Anna', age: 22, gender: 'F' }, { key: 'def', name: 'John', age: 25, gender: 'M' }, { key: 'ghi', name: 'Mary', age: 27, gender: 'F' }, { key: 'jkl', name: 'Joe', age: 30, gender: 'M' }];
const filter = [{ key: 'nonUserKey' }, { key: 'def' }, { key: 'abc' }];
const expected_result = [{ key: 'jkl', name: 'Joe', age: 30, gender: 'M' }, { key: 'def', name: 'John', age: 25, gender: 'M' }, { key: 'abc', name: 'Anna', age: 22, gender: 'F' }];
const lut = new Map(users.map(o => [o.key, o]));
const result = filter.filter(o => lut.has(o.key)).map(f => lut.get(f.key));
console.log(result);