如何根据每行的值范围对对象数组进行排序?
Posted
技术标签:
【中文标题】如何根据每行的值范围对对象数组进行排序?【英文标题】:How to sort a array of object based on range of values from each row? 【发布时间】:2021-08-21 06:57:43 【问题描述】:我有一个对象数组,其值具有范围,我想根据范围对值进行排序。首先,它应该根据 conditionalTo 进行排序,然后在有条件的 from 到 conditionalto 的范围内,它应该对计算进行排序。请帮忙 stackblitzjsfiddle 数组
[
conditionalFrom: 0, conditionalTo: 10000, computationFrom: 0, computationTo: 1000,
conditionalFrom: 10001, conditionalTo: 10000000, computationFrom: 1001, computationTo: 100000,
conditionalFrom: 10001, conditionalTo: 999999999999, computationFrom: 0, computationTo: 1000
]
预期结果
[
conditionalFrom: 0, conditionalTo: 10000, computationFrom: 0, computationTo: 1000,
conditionalFrom: 10001, conditionalTo: 999999999999, computationFrom: 0, computationTo: 1000,
conditionalFrom: 10001, conditionalTo: 10000000, computationFrom: 1001, computationTo: 100000,
]
数组
[
conditionalFrom: 10001, conditionalTo: 10000000, computationFrom: 1001, computationTo: 100000,
conditionalFrom: 0, conditionalTo: 10000, computationFrom: 1001, computationTo: 100000,
conditionalFrom: 0, conditionalTo: 10000, computationFrom: 0, computationTo: 1000,
conditionalFrom: 10001, conditionalTo: 10000000, computationFrom: 0, computationTo: 1000,
]
预期结果
[
conditionalFrom: 0, conditionalTo: 10000, computationFrom: 0, computationTo: 1000,
conditionalFrom: 0, conditionalTo: 10000, computationFrom: 1001, computationTo: 100000,
conditionalFrom: 10001, conditionalTo: 10000000, computationFrom: 0, computationTo: 1000,
conditionalFrom: 10001, conditionalTo: 10000000, computationFrom: 1001, computationTo: 100000
]
我正在使用 lodash 进行排序,但二级排序不起作用
const result = sortBy((sortBy(array, 'computationTo')), 'conditionalTo');
【问题讨论】:
是您的示例错误吗? conditionalFrom 有三个0
,但 result 有两个?
@Terry Lennox 在这种情况下,先按 conditionalTo - conditionalFrom 然后按 computeTo - computeFrom 然后根据计算范围和计算范围重新排列
【参考方案1】:
您可以自定义排序委托,例如:
arr.sort((a, b) =>
let ret = a.conditionalTo - b.conditionalTo;
if (ret !== 0)
return ret;
return a.conditionalFrom - b.conditionalFrom;
);
【讨论】:
sort
的参数告诉如何对两个数组项进行排序:a 和 b,正数是 a>b,零是 a==b,负数是 a
它应该是动态发生的......你能帮我这样做吗以上是关于如何根据每行的值范围对对象数组进行排序?的主要内容,如果未能解决你的问题,请参考以下文章