我正在使用 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/