javascript - 如何忽略lodash orderBy中的新行

标签 javascript node.js lodash

我正在使用 lodash/orderBy 订购数组。我无法控制数组中返回的内容。当我的数组项中有新行时,它们不会按照我预期的方式排序。有什么办法可以忽略新行吗?或者有其他方法可以正确订购商品吗?

const shouldBeFirst = 'My message\r\n\r\nshould consist of A A A A some 
text';
const shouldBeSecond= 'My message\r\n\r\nshould consist of \r\n\r\n some 
text';

const array = [
 { text: 'xxx' },
 { text: shouldBeFirst },
 { text: 'yyy' },
 { text: shouldBeSecond},
 { text: 'zzz' }];

const ordered = orderBy(array, ['day'], ['asc']);

我期望获得这些元素的顺序是

 { text: shouldBeFirst },
 { text: shouldBeSecond},
 { text: 'xxx' },
 { text: 'yyy' },
 { text: 'zzz' }];

但是我得到它们的顺序是:

 { text: shouldBeSecond },
 { text: shouldBeFirst },,
 { text: 'xxx' },
 { text: 'yyy' },
 { text: 'zzz' }];

[编辑:实际上我需要按更多字段排序,因此实际排序看起来更像下面的代码]

 const array = [
 { text: 'xxx', day: 'monday', hour: '12' },
 { text: shouldBeFirst, day: 'tuesday', hour: '12' },
 { text: 'yyy', day: 'wednesday', hour: '12' },
 { text: shouldBeSecond, day: 'thursday', hour: '12'},
 { text: 'zzz', day: 'friday', hour: '12' }];

const ordered = orderBy(array, ['day', 'hour', 'text'], ['asc', 'asc', 'asc']);

最佳答案

确实可以使用orderBy:

您可以使用 orderBy 来做到这一点通过提供比较函数。

const shouldBeFirst = 'My message\r\n\r\nshould consist of A A A A some text';
const shouldBeSecond= 'My message\r\n\r\nshould consist of \r\n\r\n some text';

const array = [
 { text: 'xxx' },
 { text: shouldBeFirst },
 { text: 'yyy' },
 { text: shouldBeSecond},
 { text: 'zzz' }];

const ordered = _.orderBy(array, item => item.text.replace(/\s+/g, " "));

console.log(ordered)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

如果需要,可以调整替换 - 这只是为了说明如何定义它。多个条件仍然可以作为数组传入

const shouldBeFirst = 'My message\r\n\r\nshould consist of A A A A some text';
const shouldBeSecond= 'My message\r\n\r\nshould consist of \r\n\r\n some text';

const array = [
 { text: 'xxx', value: 2 },
 { text: 'xxx', value: 1 },
 { text: shouldBeFirst },
 { text: 'yyy', value: 42 },
 { text: 'yyy', value: 12 },
 { text: shouldBeSecond},
 { text: 'zzz', value: 7 }];

//separating criteria for better readability
const criteria1 = item => item.text.replace(/\s+/g, " ");
const criteria2 = 'value'; //you can still pick by property name

//order by sanitized values of the text property first, followed by the value property
const ordered = _.orderBy(array, [criteria1, criteria2]);

console.log(ordered);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

关于javascript - 如何忽略lodash orderBy中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52408209/

相关文章:

javascript - 如何在保留非连续重复项的同时从数组中删除重复项?

javascript - 从随机部分加载页面时将类添加到标题

javascript - 在Javascript中查找另一个数组中数组的每个元素的所有出现

javascript - 如何在 lodash 中使用数组过滤条件来对抗对象?

javascript - 将 append 的相关元素保留在正文中

javascript - 替换输入字段中的错误输入

javascript - 将 G Analytics 集成到 Node.js API

node.js - 套接字超时!使用 Node telnet-client 的 Telnet 连接问题

mysql - 用于存储用户多种爱好的关系数据库结构

javascript - 通过 2 个键连接 3 个 JavaScript 数组?