代码之家  ›  专栏  ›  技术社区  ›  Sifnos

如何使用Ramda对单词数组进行排序?

  •  0
  • Sifnos  · 技术社区  · 7 年前

    使用Ramda对数字进行排序很容易。

    const sizes = ["18", "20", "16", "14"]
    console.log("Sorted sizes", R.sort((a, b) => a - b, sizes))
    //=> [ '14', '16', '18', '20' ]
    

    const trees = ["cedar", "elm", "willow", "beech"]
    console.log("Sorted trees", trees.sort())
    

    你将如何用Ramda对一系列单词进行排序。

    const trees = ["cedar", "elm", "willow", "beech"]
    console.log("Sorted trees", R.sort((a, b) => a - b, trees))
    //=> ["cedar", "elm", "willow", "beech"]
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Hans Fredric Waadeland    5 年前
    import R from 'ramda'
    
    const names = ['Khan', 'Thanos', 'Hulk']
    
    const sortNamesAsc = R.sortBy(R.identity) // alphabetically
    const sortNamesDesc = R.pipe(sortNamesAsc, R.reverse)
    
    sortNamesAsc(names) // ['Hulk', 'Khan', 'Thanos']
    sortNamesDesc(names) // ['Thanos', 'Khan', 'Hulk']
    

    Ramda Repl example

        2
  •  10
  •   CertainPerformance    7 年前

    别想这么做 字符串-使用 localeCompare

    const trees = ["cedar", "elm", "willow", "beech"]
    console.log("Sorted trees", R.sort((a, b) => a.localeCompare(b), trees))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
        3
  •  7
  •   Ori Drori    7 年前

    您可以使用 R.comparator R.lt :

    const trees = ["cedar", "elm", "willow", "beech"]
    const result = R.sort(R.comparator(R.lt), trees)
    console.log("Sorted trees", result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
        4
  •  0
  •   user10431233 user10431233    7 年前

    这就是你所说的用拉姆达排列单词的意思吗?

    import R from 'ramda'
    var objs = [ 
        { first_name: 'x', last_name: 'a'     },
        { first_name: 'y',    last_name: 'b'   },
        { first_name: 'z', last_name: 'c' }
    ];
    var ascendingSortedObjs = R.sortBy(R.prop('last_nom'), objs)
    var descendingSortedObjs = R.reverse(ascendingSortedObjs)