Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array by array field value javascript

I have the following array:

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online'     },
    { id: '8YSHJ',    name: 'mary', presence: 'offline'   },
    { id: '7XHSK', name: 'rene', presence: 'online' }
];

I want to sort the array so it returns a new array by 'presence': 'online' users displaying first before offline items.

So if sorted, it should return something like this:

var objs = [ 
    { id: 'X82ns', name: 'james', presence: 'online' },
    { id: '7XHSK', name: 'rene', presence: 'online' },
    { id: '8YSHJ',    name: 'mary', presence: 'offline' }
];

Something like this:

const newArray = objs.sort((a, b) => {
      if (a.presence === 'online') {
        return 1;
      } else if (b.presence === 'offline') {
        return -1;
      } else {
        return 0;
      }
    })

return newArray;
}

What is the right way to get the expected result?

like image 589
Ericky Avatar asked Aug 17 '26 11:08

Ericky


1 Answers

You can use localeCompare method.

var objs = [ { id: 'X82ns', name: 'james', presence: 'online' }, { id: '8YSHJ', name: 'mary', presence: 'offline' }, { id: '7XHSK', name: 'rene', presence: 'online' } ];

objs.sort((a,b) => b.presence.localeCompare(a.presence));
console.log(objs);

Don't forget that the sort() method sorts the elements of an array in place so you do not need to use const newArray = objs.sort....

like image 98
Mihai Alexandru-Ionut Avatar answered Aug 19 '26 23:08

Mihai Alexandru-Ionut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!