I've been finding that for a lot of code I've been writing recently, it naively might look like this:
Array approach:
const options = [
{
id: 'red',
label: 'Red',
data: '#f00'
},
{
id: 'blue',
label: 'Blue',
data: '#00f'
}
];
And then something like, in say React context (but my question relates to programming generally):
return <select>
{options.map((v) => <option key = {v.id} value = {v.id}>{v.label}</option>}
</select>;
Now the problem with storing the list of options as an array is that if you ever need to look up an options object by just an id, you have to do a full scan over the array like:
function findOptionById(id) {
return options.find((v) => v.id === id);
}
Which doesn't seem particularly efficient (if this function is being called every render for example) and becomes particularly problematic when you have nested objects.
So the alternative:
Map approach:
const options = {
red: {
id: 'red',
label: 'Red',
data: '#f00'
},
blue: {
id: 'blue',
label: 'Blue',
data: '#00f'
}
};
Mapping over it:
Object.values(options).map((v) => <options key={v.id} value={v.id}>{v.label}</option>)
Finding an item in the list:
function findOptionById(id) {
return options[id]
}
Faster lookup (I believe? or am I wrong in the context of javascript specifically?), and has the added advantage of enforcing some kind of ID uniqueness which is in my scenarios is always necessary.
My question(s)
It seems to me that in a scenario where 'You have a list of items, and they have some kind of unique key' then a map is always (or usually) advantageous to use.
However, from a code readability and 'the data structures make sense' POV, using arrays seems more intuitive.
That is for example, if I am creating a RadioList component and I'm saying 'it has an options
property which is a list of items containing id, label, and data', then declaring this type as an array it's a lot more obvious to the user what the meaning of this property is.
Is there some kind of term or concept in software engineering that considers when an array should be used vs a map?
Edit: Although I've mentioned performance, it's not really my main concern. My main concern is around the ease of use of this list object, inserting, removing, looking up items etc.