码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript + lodash] sortBy and sortedIndex

时间:2015-03-04 06:13:41      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

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‘ } ]
*/

 

[Javascript + lodash] sortBy and sortedIndex

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/4312267.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!