alex
alex

Reputation: 1350

Sorting a JavaScript array of objects does not work

I have the following JavaScript object:
The output of console.log(myObject) is:

[Object, Object]
0: Object
data: Array[19]
label: "Orange"
__proto__: Object
1: Object
data: Array[19]
label: "Black"
__proto__: Object
length: 2
__proto__: Array[0]

I need to sort the object by label

I've tried:

myObject.sort(function(a, b){ 
    return a.label - b.label;
});

Which doesn't seem to work.

Q: How can I sort the object by label?

Upvotes: 0

Views: 33

Answers (1)

user1106925
user1106925

Reputation:

You're preforming subtraction on a string, which doesn't make sense. Instead, use .localeCompare

myObject.sort(function(a, b){ 
    return a.label.localeCompare(b.label);
});

This method returns a negative number if a is less than b, a positive number if a is greater than b or 0 if equal.

Because the .sort() method expects a numeric value from the callback, this works perfectly.

You could also use comparison operators, though this isn't quite the same as .localeCompare(), which performs more sophisticated comparison of unicode characters rather than simple byte comparison.

myObject.sort(function(a, b){ 
    return a.label < b.label ? -1 : a.label > b.label ? 1 : 0;
});

Upvotes: 4

Related Questions