【发布时间】:2021-08-22 05:12:03
【问题描述】:
我有一个包含以下元素的数组,
let stats = [
{ 'keyword': 'testing', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing software', 'searches': 235, 'isAnalysed': true },
{ 'keyword': 'the testing', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing the boundries', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing business ideas', 'searches': 155, 'isAnalysed': true },
{ 'keyword': 'testing electronics', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing and assessment', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing microservices', 'searches': 65, 'isAnalysed': true },
];
我想将数组排序为如下所示,
升序;
let stats = [
{ 'keyword': 'testing microservices', 'searches': 65, 'isAnalysed': true },
{ 'keyword': 'testing business ideas', 'searches': 155, 'isAnalysed': true },
{ 'keyword': 'testing software', 'searches': 235, 'isAnalysed': true },
{ 'keyword': 'testing', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'the testing', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing the boundries', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing electronics', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing and assessment', 'searches': 0, 'isAnalysed': false },
];
降序;
let stats = [
{ 'keyword': 'testing software', 'searches': 235, 'isAnalysed': true },
{ 'keyword': 'testing business ideas', 'searches': 155, 'isAnalysed': true },
{ 'keyword': 'testing microservices', 'searches': 65, 'isAnalysed': true },
{ 'keyword': 'testing', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'the testing', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing the boundries', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing electronics', 'searches': 0, 'isAnalysed': false },
{ 'keyword': 'testing and assessment', 'searches': 0, 'isAnalysed': false },
];
是的,如果该对象为isAnalysed = true,我想按searches 排序。我正在使用LodashorderBy()。这是我为此编写的排序代码段。
// direction - asc/desc
const sortedData = _.orderBy(stats, [function (object) {
if (object.isAnalysed === true) return object.searches;
}], [direction]);
但这会像searches 完成的普通排序一样对整个数组进行排序。我在这里错过了什么?
【问题讨论】:
-
你必须使用 lodash 吗?
filter、sort和concat应该可以解决它。
标签: javascript sorting lodash