sortBy:
var collection = ['John', 'Petteri', 'Antti', 'Joonas', 'Zhentian']; var sorted = _.sortBy(collection); //[ 'Antti', 'John', 'Joonas', 'Petteri', 'Zhentian' ]
var collection = ['John', 'Petteri', 'Antti', 'Joonas', 'Zhentian']; var sorted = _.sortBy(collection).reverse(); //[ 'Zhentian', 'Petteri', 'Joonas', 'John', 'Antti' ]
var collection = [ {age: 90, name: "Zach"}, {age: 33,name: "Beth"}, {age: 8,name: "Yolanda"}, {age: 57,name: "Chris"}, {age: 80,name: "Abe"} ]; var sorted = _.sortBy(collection, "age"); /* [ { age: 8, name: 'Yolanda' }, { age: 33, name: 'Beth' }, { age: 57, name: 'Chris' }, { age: 80, name: 'Abe' }, { age: 90, name: 'Zach' } ] */
sortedIndex:
var collection = [ {age: 90, name: "Zach"}, {age: 33,name: "Beth"}, {age: 8,name: "Yolanda"}, {age: 57,name: "Chris"}, {age: 80,name: "Abe"} ]; var newGuy = {age: 26, name: "Wan"}; var sortedCollection = _.sortBy(collection, "age"); console.log(sortedCollection); //Want to insert an new guy, first find his a position in the array var index = _.sortedIndex(sortedCollection, newGuy, "age"); console.log(index); // 1 //insert into the array. sortedCollection.splice(index, 0, newGuy); /* [ { age: 8, name: 'Yolanda' }, { age: 26, name: 'Wan' }, { age: 33, name: 'Beth' }, { age: 57, name: 'Chris' }, { age: 80, name: 'Abe' }, { age: 90, name: 'Zach' } ] */
本文介绍了使用 Underscore.js 库进行数组排序的方法,包括基本字符串排序、逆序排序及根据对象属性排序,并展示了如何利用 sortedIndex 方法找到新元素在已排序数组中的正确位置。
860

被折叠的 条评论
为什么被折叠?



