Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 27, 2023 12:11 am GMT

JavaScript tip to efficiently search in long arrays and save performance

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

  1. Create a new empty object
  2. Map our array to be keys and values in our object, Keys are what we search by, And values are the object itself
  3. 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:

  1. Time complexity for searching in arrays is O(n)
  2. Time complexity for indexing an object attribute is O(1)
  3. 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!


Original Link: https://dev.to/rem0nfawzi/javascript-tip-to-efficiently-search-in-long-arrays-and-save-performance-1914

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To