1

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)

3
  • 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 Commented Jul 7, 2020 at 14:08
  • Try array.sort((a, b) => a[1].author.localeCompare(b[1].author)) Commented Jul 7, 2020 at 14:09
  • Thanks for the advice. The data structure comes from an [import function loading markdown files into a JSON] (npmjs.com/package/markdown-to-json) object. Now my target is to return this sorted as described. Commented Jul 7, 2020 at 15:00

2 Answers 2

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)) 
Sign up to request clarification or add additional context in comments.

1 Comment

Dupe............
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.