Javscript sort array of objects

In this post, I will show you how to sort array elements in javascript.
In javascript array have one method sort which accepts one optional argument compareFn which compare two elements of the array.

const fruits=['Orange','Mango','Kiwi','Apple'];
fruits.sort();
// OUTPUT
["Apple", "Kiwi", "Mango", "Orange"]

Let’s use the sort method on array of numbers.

const numbers=[1,11,2,15,10];
numbers.sort()
//OUTPUT
[1, 10, 11, 15, 2]

🤷‍♀️ The array is not sorted why?
Javascript sort function sorts values as string.
If you want to sort numeric value, then you have to pass compare function in the sort function as shown below

numbers.sort(function(a,b){
  if(a>b)
	  return 1;
else 
	return -1;
});

If you are using ES5/6 then you can use arraow function

- numbers.sort(function(a,b){
+ numbers.sort((a,b)=>{
  if(a>b)
	  return 1;
else 
	return -1;
});

You can also refactor the code using javascript ternaory operator

- numbers.sort(function(a,b){
- numbers.sort((a,b)=>{
-  if(a>b)
-	  return 1;
- else 
-	return -1;
- });
+ numbers.sort((a,b)=>a>b?1:-1);

How to sort array of objects.

If you want to sort complex objects in javascript, you have to tell javascript how to compare each element of the object.
Let’s consider the following array of objects

const fruits = [{
    name: "Apple",
    price: 35,
    weight: 0.5,
},
{
    name: "Banana",
    price: 12,
    weight: 0.4,
},
{
    name: "Grapes",
    weight: 0.1,
    price: 45
},
{
    name: "Pineapple",
    price: 200,
    weight: 1
}
];

let’s suppose you want to sort the array by property price in ascending order

const results = fruits.sort((a, b) => a.price > b.price ? 1 : -1);
console.log(results);
// OUTPUT
[
  { name: 'Banana', price: 12, weight: 0.4 },
  { name: 'Apple', price: 35, weight: 0.5 },
  { name: 'Grapes', price: 45, weight: 0.1 },
  { name: 'Pineapple', price: 200, weight: 1 }
]

You can see the array is sorted by price in ascending order

How to sort array of objects by multiple property

const results = fruits.sort((a, b) => {
    if (a.name > b.name) {
        return 1
    } else {
        if (a.name === b.name) {
            if (a.price > b.price) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    }

});
Reactions

Post a Comment

0 Comments

Close Menu