[Javascript + lodash] sortBy and sortedIndex
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' } ] */