Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array of Objects by specific key value | Javascript [duplicate]

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 :|

like image 874
TJBlackman Avatar asked May 06 '17 03:05

TJBlackman


People also ask

How do you sort an array of objects based on a key?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

How will you sort an array with many duplicate values?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.

How do you sort an array of objects by string?

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

Can I sort the object keys JavaScript?

To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.


1 Answers

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

like image 186
brk Avatar answered Oct 26 '22 15:10

brk