15 February 2015

How to use 'Object Like Array' in JavaScript

Imagine we have array of 'students' in JavaScript, which we got from server.

If we have this kind of array then we can easily access student using Array Index.
something like

students[0], students[1],

But wait, we also want to do something like

students["aaa"], that is,  I want to access students using their unique Id too, much like object notation -
Ex should also return proper student.

Again, I want to group them with their subjects too,
for example,
students.Math should return Array of all students who has "Math" subject

the normal approach is to create function which do parsing again and again over the Array and give proper result. but Here i have very sweet trick.

Here we go,

So, In the above trick , student.length is not affected, it will remain 3. So after running above code, we have 'students' Array (more precisely - Object Like Array ), like this.

Now, by this method,
students[0],, students.Math[0] will be same,
It means

students[0] === === students.Math[0]

More over, If you do change like this

students[0].name = "A-Modified";
then it will automatically reflected everywhere,
So it means, === "A-Modified";

Hope, now you can start using Object Like Array.