JavaScript Solutions, Competitive programming in JavaScript, MCQ in JS

Tuesday, 8 January 2019

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 ));
}
arrObject.sort(sortJSONArray);

Now use our arrObject to sort it out.
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.


No comments:

Post a Comment