0

I'm looking to do a custom sort on an array based on one of its attributes. So for example if I have a person object:

var person = {name:""};

and I want to sort on name but not alphabetically. So if I have:

  • Tim
  • Mike
  • Jen
  • Ashley

but I want this to be sorted:

  • Mike
  • Ashley
  • Tim
  • Jen

How would I accomplish this? I know I can use a function to compare:

array.sort(function(x, y) {
  if (x < y) {
    return -1;
  }
  if (x > y) {
    return 1;
  }
  return 0;
});

But this would result in an alphabetical sort. Then I thought if there was a way to assign a numerical value to each potential name (I will have a known, limited set) then to try that, but I'm not sure it's the correct approach. Any help would be appreciated!

Ryan Sayles
  • 3,389
  • 11
  • 56
  • 79
  • 1
    but how are they sorted then? – Daniel A. White Apr 17 '19 at 19:47
  • take an object with the names as key and a number as value (maybe without zero) if you have unknown names (this names can be sorted to start, end or any other place) and sort by this value or take a default value, like `Infinity` or `-Infinity`. please have a look to the duplicate target. – Nina Scholz Apr 17 '19 at 19:51

0 Answers0