0

Searching many examples I didn't manage to solve my case. I have an array that should be sorted by author. My attempt did nothing. What is the right expression?

var array = [
  ["ifke", {
    "title": "secure",
    "author": "admin"
  }],
  ["lottery", {
    "title": "The lo",
    "author": "anton"
  }],
  ["short-content", {
    "title": "Short Content",
    "author": "scott"

  }],
  ["ziddler", {
    "title": "The Fiddler",
    "author": "herman"

  }]
];


array.sort((a, b) => a[1].author - b[1].author)
console.log(array)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Fred
  • 417
  • 5
  • 16
  • 3
    Ok before even attempting to answer, may I ask why your data is structured that way? It's awful. Because if this isn't just homework assignment, then I'd strongly advice re-thinking the way you store data – Samuel Hulla Jul 07 '20 at 14:08
  • Try `array.sort((a, b) => a[1].author.localeCompare(b[1].author))` – User863 Jul 07 '20 at 14:09
  • Thanks for the advice. The data structure comes from an [import function loading markdown files into a JSON] (https://www.npmjs.com/package/markdown-to-json) object. Now my target is to return this sorted as described. – Fred Jul 07 '20 at 15:00

2 Answers2

2

A working solution using .sort method of an array and using localeCompare method to sort based on the strings

var array = [
 [ "ifke", {
    "title": "secure",
    "author": "admin"
  }],
  ["lottery", {
    "title": "The lo",
    "author": "anton"
  }],
  ["short-content", {
    "title": "Short Content",
    "author": "scott"
  
  }],
  ["ziddler", {
    "title": "The Fiddler",
    "author": "herman"

  }]
];

array.sort((a,b) => a[1].author.localeCompare(b[1].author));
console.log(array);
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
2

You have the right idea, but you need to use a differet way of comparing. The subtraction operator on non-numeric strings always yields NaN, which is useless for comparison.

You could use localeCompare, which reutrns 1, 0, or -1:

array.sort((a, b) => a[1].author.localeCompare(b[1].author))
apsillers
  • 112,806
  • 17
  • 235
  • 239