简体   繁体   中英

Underscore JS - Sorting an Array of Objects

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?

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"} ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM