I have an array of objects
const a = [
{ name: 'z', items: [..] },
{ name: 'x', items: [..] },
{ name: 'y', items: [..] },
{ name: 'a', items: [..] },
]
I would like to select and reorder such that I transform the array into
const a_new = [
{ name: 'x', items: [..] },
{ name: 'y', items: [..] },
{ name: 'z', items: [..] },
]
i.e. I only want those with name x, y, and z and I want it ordered by some specific order (not just alphanumerically).
So I would like to, for instance, specify an array ['x', 'y', 'z'], indicating which names I would allow and how they should be sorted.
Could it be something like
['x', 'y', 'z'].map(allowedValue => a.find(b => b.name === allowedValue))
It just seems a bit memory heavy?
filterandsortas indicated by your title?['x', 'y', 'z'].map(allowedValue => a.find(b => b.name === allowedValue))? What do you mean by "memory heavy"?reduceato a “hash map” object where the keys are the values of thenameproperty of each object, then map["x", "y", "z"]to the objects that you can look up from the hash map. This should yield a time complexity of O(n), but the space complexity would be worse.