0

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?

1
  • Try 'Orange' - 'Black' in the console. Commented Dec 3, 2015 at 16:49

1 Answer 1

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.