[Ramda] Sort, SortBy, SortWith in Ramda

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Ramda] Sort, SortBy, SortWith in Ramda相关的知识,希望对你有一定的参考价值。

The difference between sort, sortBy, sortWith is that:

1. sort: take function as args.

2. sortBy: take prop as args.

3. sortWith: take array of funcs as args.

 

const R = require(‘ramda‘);

const {sort, sortBy, sortWith, descend, prop, ascend} = R;

const sample = [
    {name: "Sally", age: 29, height: 65},
    {name: "Zac", age: 29, height: 72},
    {name: "John", age: 32, height: 61},
    {name: "Lisa", age: 28, height: 63},
    {name: "Bob", age: 29, height: 66},
    {name: "Allen", age: 29, height: 66}
];

const heightDescending = descend(prop(‘height‘));
const ageDescending = descend(prop(‘age‘));
const nameAscending = ascend(prop(‘name‘));

const sortWithCondition = sortWith([
                                       heightDescending,
                                       ageDescending,
                                       nameAscending
                                   ]);

const result = sortWithCondition(sample);
/*
* [ { name: ‘Zac‘, age: 29, height: 72 },
  { name: ‘Allen‘, age: 29, height: 66 },
  { name: ‘Bob‘, age: 29, height: 66 },
  { name: ‘Sally‘, age: 29, height: 65 },
  { name: ‘Lisa‘, age: 28, height: 63 },
  { name: ‘John‘, age: 32, height: 61 } ]
* */
console.log(result);

/*
* sort: take function
* */
const sortByNameDescending = sort(descend(prop(‘name‘)));
const result1 = sortByNameDescending(sample);
/*
* [ { name: ‘Zac‘, age: 29, height: 72 },
  { name: ‘Sally‘, age: 29, height: 65 },
  { name: ‘Lisa‘, age: 28, height: 63 },
  { name: ‘John‘, age: 32, height: 61 },
  { name: ‘Bob‘, age: 29, height: 66 },
  { name: ‘Allen‘, age: 29, height: 66 } ]
* */
console.log("sortByNameDescending:", result1);


/*
* sortBy: take prop
* */
const age = prop(‘age‘);
const result2 = sortBy(age);
/*
* [ { name: ‘Lisa‘, age: 28, height: 63 },
  { name: ‘Sally‘, age: 29, height: 65 },
  { name: ‘Zac‘, age: 29, height: 72 },
  { name: ‘Bob‘, age: 29, height: 66 },
  { name: ‘Allen‘, age: 29, height: 66 },
  { name: ‘John‘, age: 32, height: 61 } ]
* */
console.log(result2(sample));

 

以上是关于[Ramda] Sort, SortBy, SortWith in Ramda的主要内容,如果未能解决你的问题,请参考以下文章

order by 和 sort by 的区别

JavaScript中sort()方法

JavaScript数组sort()方法小结

JavaScript sort() 方法

何时在 hive QL 中使用 sort By 子句

JavaScript sort函数的使用