Let's assume We've this array contains 100 elements
const arr = [
{
id: 1,
value: "Hello 1",
},
{
id: 2,
value: "Hello 2",
},
.....
{
id: 100,
value: "Hello 100",
},
];
When we try to search for any element in this array by ID for example
const element50 = arr.find(el => el.id === 50);
The time complexity here is O(n), n is the number of array elements, Which means in the worst case if I'm looking for the last element, It'll loop on all array elements to find that last element, And if We search a lot in this array it'll affect app performance so badly.
What we can do here is mapping this array to be an object of keys and values, Keys are the item we search by, In our case it's the ID, And values are the remaining attributes ...
So let's create our new object
const arr = [
{
id: 1,
value: "Hello 1",
},
{
id: 2,
value: "Hello 2",
},
{
id: 100,
value: "Hello 100",
},
];
let arrayMap = {};
arr.forEach(el => {arrayMap[el.id] = el});
Now our object arrayMap will be like this
{
1: {
id: 1,
value: "Hello 1",
},
2: {
id: 2,
value: "Hello 2",
},
....
100: {
id: 100,
value: "Hello 2",
},
}
So now if we want the 50th element We'll do this
const element50 = arrayMap[50];
Now time complexity will be O(1), It won't loop on other elements to find the element we want, It'll just get it as an attribute from our new object .. By this We'll save a lot of operations especially if We search a lot in a large array.
So here're the steps We follow to make search in arrays more efficient
- Create a new empty object
- Map our array to be keys and values in our object, Keys are what we search by, And values are the object itself
- We search using object square brackets, EX: obj[id]
The only one limitation when using this trick is that We can only search for an exact value, For example we can't use it to search for an element that includes a specific text, But we can do for an element that exactly equals a specific text.
Conclusion:
- Time complexity for searching in arrays is O(n)
- Time complexity for indexing an object attribute is O(1)
- By mapping our array to an object then find elements by indexing this object, We decrease time complexity from O(n) to O(1)
Happy coding!
Top comments (2)
This can be a useful tip under certain conditions when you expect to be doing a lot of lookups on a very large array.
It's worth noting, though, that the function to convert the array into an object is quite expensive and also has O(n) complexity.
To get any substantial performance benefit I wouldn't use this approach if:
Use reduce instead of forEach 👍