2

I have an array made up of 80 individual objects. Within those individual objects I have a key: value pair. The key is "number" and values go from "0001" to "0080".

So the structure would be something like

 myArray = [{number: "0001"}, {number: "0002"}, {number: "0003"} ]

and so on...

I'm using Underscore, but I'm having trouble figuring out a way to order the individual objects so they're sorted 1,2,3,5. The values that are number are also strings.

Any suggestions?

3
  • 1
    That's invalid syntax. Can you show us what kind of objects you really have in JSON? Commented Jul 28, 2015 at 14:08
  • 1
    Look at this link : stackoverflow.com/questions/15334015/sort-nested-array-by-value Commented Jul 28, 2015 at 14:09
  • 1
    Looks like that key is useless and you should just go for _.pluck(…, "number") before sorting. Commented Jul 28, 2015 at 14:09

1 Answer 1

5

Use sortBy function:

var myArray = [{number: "0003"}, {number: "0001"},{number: "0002"} ];
var result = _.sortBy(myArray, "number");
console.log(result);
<script src="http://underscorejs.org/underscore.js"></script>

results in:

[{number: "0001"}, {number: "0002"},{number: "0003"} ]

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.