简体   繁体   中英

Sort a array of objects lexicographically based on a nested value

Using Javascript, I would like to know how to sort lexicographically a array of objects based on a string value in each object.

Consider:

[
 {
    "name" : "bob",
    "count" : true
    "birthday" : 1972
 },
      {
    "name" : "jill",
    "count" : false
    "birthday" : 1922
 },
      {
    "name" : "Gerald",
    "count" : true
    "birthday" : 1920
 }
 ]

How can I sort the array alphabetically by name? The name values are usernames, so I would like to maintain the letter casing.

var obj = [...];

obj.sort(function(a,b){return a.name.localeCompare(b.name); });

Be aware that this will not take capitalisation into account (so it will order all names beginning with capitals before all those beginning with smalls, ie "Z" < "a" ), so you might find it relevant to add a toUpperCase() in there.

You can make it more generic as well:

function sortFactory(prop) {
   return function(a,b){ return a[prop].localeCompare(b[prop]); };
}

obj.sort(sortFactory('name')); // sort by name property
obj.sort(sortFactory('surname')); // sort by surname property

And even more generic if you pass the comparator to the factory...

This will do it:

arr.sort(function(a, b) {
    return a.name.localeCompare(b.name);
});

Using comparison

arr.sort(function (a, b) {return a.name.toLowerCase() > b.name.toLowerCase()})

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#Comparing_strings

I read in this post sort array lexicographically in javascript to just use sort directly and not localeCompare and this seems to do the trick.

localeCompare does not sort lexicographically.

'aaA'.localeCompare('aAA') returns -1 which sorts aaA before aAA . In lex, capitals come first, so it should be ['aAA', 'aaA']

You can do something like this to handle a few cases.

export default function sortLex ({ arr, prop, reverse }) {
  let sorted
  if (prop) {
    sorted = arr.sort(sortFactory(prop))
  } else sorted = arr.sort(sort)

  return reverse ? sorted.reverse() : sorted
}

function sort (a, b) {
  if (a < b) {
    return -1
  }
  if (a === b) {
    return 0
  }
  if (a > b) {
    return 1
  }
}

function sortFactory (prop) {
  return (a, b) => {
    return sort(a[prop], b[prop])
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM