I have an array of items which I sometimes need to iterate and sometimes access a member directly. So I decided to keep references in two variables, one array and one object. I do something like this:
const itemsArr = [];
const itemsObj = {};
const addItem = (data) => {
const item = {
id: data.id,
name: data.name
};
itemsArr.push(item);
itemsObj[data.id] = item;
}
const removeItem = (data) => {
let i;
for (i = 0; i < itemsArr.length; i++) {
if (itemsArr[i].id === data.id) {
itemsArr.splice(i, 1);
break;
}
}
itemsObj[data.id] = null;
delete itemsObj[data.id];
}
const getWithId = (id) => {
return itemsObj[id];
}
const getWithName = (name) => {
let i;
for (i = 0; i < itemsArr.length; i++) {
if (itemsArr[i].name === name) {
return itemsArr[i];
}
}
return null
}
So I manage two objects and use one or another depending on the task, I feel like this is the most performant way but maybe there are better ways for this, like a Map or Set.
Is there a single JavaScript data structure that will outperform arrays in iteration and objects in lookup?
I think Object.keys have additional performance costs for iterating an object, similarly Array.filter for lookup on an array, so my intuition is to use arrays for iteration and objects for lookup, but if there is a single data structure that is optimized for both, I would like to know and use only one items in my code.
Thanks
idorname?dateCreatedetc but I just wrote two for simplicity.