用JavaScript中的两个属性对对象数组进行排序
假设我们有一个像这样的对象数组-
const arr = [ { resVal: "25FA15", resFlow: 49, resName: "Rendimiento Tri−Seal Completo", resPhoto: "Tri−Sealseries.png", resHP: 1.5 }, { resVal: "25FA2", resFlow: 52, resName: "Rendimiento Tri−Seal Completo", resPhoto: "Tri−Sealseries.png", resHP: 2 }, { resVal: "45FA2", resFlow: 53, resName: "Rendimiento Hi−Cap Completo", resPhoto: "HighCapseries.png", resHP: 2 }, { resVal: "35FA2", resFlow: 59, resName: "Rendimiento Hi−Cap Completo", resPhoto: "HighCapseries.png", resHP: 2 } ];
我们需要编写一个JavaScript函数,该函数接受一个这样的对象数组。函数应基于两个不同的属性对该数组进行排序-
按较高的“resFlow”值排序,
但“resHP”值最低。
方法
我们对指定的键顺序及其排序顺序使用链式方法。
数组按属性排序-
resHP,升序和
resFlow,降序。
它可以计算增量,这反映了两个对象的关系。如果该值为零,则两个值相等,并计算并返回下一个增量。
示例
为此的代码将是-
const arr = [ { resVal: "25FA15", resFlow: 49, resName: "Rendimiento Tri−Seal Completo", resPhoto: "Tri−Sealseries.png", resHP: 1.5 }, { resVal: "25FA2", resFlow: 52, resName: "Rendimiento Tri−Seal Completo", resPhoto: "Tri−Sealseries.png", resHP: 2 }, { resVal: "45FA2", resFlow: 53, resName: "Rendimiento Hi−Cap Completo", resPhoto: "HighCapseries.png", resHP: 2 }, { resVal: "35FA2", resFlow: 59, resName: "Rendimiento Hi−Cap Completo", resPhoto: "HighCapseries.png", resHP: 2 } ]; const sortByTwo = (arr = []) => { arr.sort((a, b) => { return a.resHP − b.resHP || b.resFlow − a.resFlow; }); }; sortByTwo(arr); console.log(arr);
输出结果
控制台中的输出将是-
[ { resVal: '25FA15', resFlow: 49, resName: 'Rendimiento Tri−Seal Completo', resPhoto: 'Tri−Sealseries.png', resHP: 1.5 }, { resVal: '35FA2', resFlow: 59, resName: 'Rendimiento Hi−Cap Completo', resPhoto: 'HighCapseries.png', resHP: 2 }, { resVal: '45FA2', resFlow: 53, resName: 'Rendimiento Hi−Cap Completo', resPhoto: 'HighCapseries.png', resHP: 2 }, { resVal: '25FA2', resFlow: 52, resName: 'Rendimiento Tri−Seal Completo', resPhoto: 'Tri−Sealseries.png', resHP: 2 } ]