7

I'm having trouble sorting a specific array of objects from a small personal project I'm working on. I have never had trouble using the Array.prototype.sort() function before, but I wonder if something about the multiple object keys is affecting it...

Been staring at it for longer than I care to admit and just need to ask for help now. :|

Goal: Sort array of objects alphabetically relative to a specific key.value on each of them.

Thanks in advance!

JS Fiddle Here

Sort function example - (I recommend looking at the full Fiddle for context though).

var sorted = array.sort((a, b) => { return a.key > b.key; });

SOLVED

@Ryan helped me find that returned a boolean isn't enough, you need to explicitly return a positive or negative number, or 0.

@Brk showed me an awesome quick way to do it.

This post has a very detailed description. Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

Thanks all! Sorry for the duplicate post :|

3
  • 1
    The sort comparison function should return -1 if a < b, 0 if a = b, or 1 if a > b.
    – Ry-
    Commented May 6, 2017 at 3:58
  • I thought returning true / false would be good enough, it always has been before. But your comment inspired me to search again and I found this article... stackoverflow.com/questions/24080785/… Ok... So annoying. Thanks though!
    – TJBlackman
    Commented May 6, 2017 at 4:02
  • @Ryan Note that it isn't required to return the specific values 1 or -1. Any positive or negative value is treated the same. Commented May 6, 2017 at 5:03

1 Answer 1

9

You can use localeCompare method which will returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

var sorted = array.sort((a, b) => {
  return a.subreddit.localeCompare(b.subreddit)
});

DEMO

3
  • This is awesome! Thanks!!
    – TJBlackman
    Commented May 6, 2017 at 4:04
  • @TJBlackman thanks & happy to help
    – brk
    Commented May 6, 2017 at 4:09
  • You are thopu boss Commented Mar 24, 2022 at 15:19

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.