I rewrote Array in JavaScript but as Object!

Rakesh Purohit
3 min readMar 13, 2022

--

Nearly everything in JS is an object.

Note: I could have used OOP to make the code better, reusable and robust. I was in so hurry to try out the experiment and do some code as talk is cheap. (😉)

Well, it is true. Even [a,r,r,a,y] is also an object in JavaScript.

I have heard that too often. Also, I had only one inquiry. “HOW?” When I began my excursion in Javascript, I had this idea. What’s more, as I continued to learn, I discovered that inside javascript regards the Array as JSON.

I had this data for quite a while as a javascript developer. One great day, while getting back, this thought hit me (and not a vehicle 🚗), assuming somebody could get it done, Why mightn’t? Why not make an effort to execute an array in JavaScript Object all alone to perceive how it functions? It would be enjoyable. I have the beneath picture as wallpaper:

A Richard Feynman Quote

Hold on before we go to the code!

To demonstrate that, I have funInJS

Talk is still cheap.

  1. An array starting with 0 the index and 0 length
  2. addElement() function as .push() increment the length by 1.

So, internally it is treated as an object which is an index as key and value as your "value"

How JavaScript might be treating an object as an array

But for users, it will always be as follows:

Limitations:

As I wrote this, this is still a baby array that is identical to an array but not the whole array, which we use in daily JavaScript. I won’t even recommend this.

Currently, This only supports number and string. It doesn’t support arrays or objects as values yet. Maybe on the next iteration.

Likewise, I have implemented below methods:

  1. deleteElement() as in .pop() (need to improve based on location or value) [Accepting PRs]
  2. maximumElement() Get the maximum element.
  3. secondMaximumElement() : Get the 2nd maximum element.
  4. checkIfArrayIsSorted() : Check if an array is sorted or not.
  5. printMeReverse() : Print the array in reverse order
  6. searchByIndex() : Search by index to know the value.
  7. searchByValue() : Search by value to know the position.

We still have a highway to implement like filter,shift ,unshift, every,some, forEach, map, reduce, fill, etc.

Well !! Numerous senior engineers will peruse this article. Go ahead and remark or give criticism. I would invite your perspectives to connect and develop.

I should go now for another article.

LinkedIn Twitter GitHub

--

--