Published On: January 27th, 2023Categories: AI News

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",
  },
];
Enter fullscreen mode

Exit fullscreen mode

When we try to search for any element in this array by ID for example

const element50 = arr.find(el => el.id === 50);
Enter fullscreen mode

Exit fullscreen mode

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 = [
  {
 ...

Source link

Leave A Comment