zoukankan      html  css  js  c++  java
  • [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' } ]
    */
  • 相关阅读:
    python中list的一种取值方式切片
    python之字典(Dictionary)
    表示数字
    自动收售货系统
    明明的随机数
    自守数
    等差数列
    计算字符个数
    字符统计
    Redraimen的走法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4312267.html
Copyright © 2011-2022 走看看