How to sort array by array field value javascript

  • A+
Category:Languages

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?


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....

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: