Mastering in JavaScript | Sort multidimensional Array

If you are a Javascript developer then you surely come to a place where you have to sort JSON object or another word sort javascript array of object by key.

So today I will show you how can you sort your JSON object with alphabetic order.

Let's take an example of the following array.



var arrObject = [

      { "id": 0, "userName": "Vikas Kad", "age":26 },

      { "id": 1, "userName": "Akshay Shelke", "age":29 },

      { "id": 2, "userName": "Rahul Konde", "age":22 }

   ];


Now here is the output if we log this array object.

Javascrit sort multidimensional array



So let's create a function to sort the array object.


function sortJSONArray(value1,value2) {
  return ((value1.userName == value2.userName) ? 0 : ((value1.userName > value2.userName) ? 1 : -1 ));
}

Now use our arrObject to sort it out.

arrObject.sort(sortJSONArray);
So output will be like this.

javascript sort array of object


now you can see our array object sorted with userName, we have used javascript's sort function and passed the function which we have created.

That's it your multidimensional array object sorted now.

Now if you want to sort your object with age then you have to make a slight change in your function. Let us create another function to sort JSON array with age.



function sortJSONArrayByAge(value1,value2) {
  return value1.age-value2.age;
}
Now you just have to call the same array with this function.

arrObject.sort(sortJSONArrayByAge);


And the output will be like this.

javascript sort array of objects by number

That's it now your javascript array object is sorted with the number as well.


Mastering in JavaScript | Sort multidimensional Array Mastering in JavaScript | Sort multidimensional Array Reviewed by Vikas Kad on Tuesday, January 08, 2019 Rating: 5

No comments:

Powered by Blogger.