按属性对对象数组进行排序(具有自定义顺序,而不是字母顺序)

我想就这个小问题得到您的帮助。


我想根据代码值而不是字母顺序对数组进行排序。 (我用粗体字指定了该名称,但最终还是被标记出来了,人们甚至都不在乎阅读该问题)


例如,我想有所有绿色的对象,那么所有的蓝色的人,然后将所有的红色的。最好的方法是什么?


[

    { code: "RED", value: 0},

    { code: "BLUE", value: 0},

    { code: "RED", value: 0},

    { code: "GREEN", value: 0},

    { code: "BLUE", value: 0},

    { code: "RED", value: 0},

    { code: "GREEN", value: 0},

    { code: "BLUE", value: 0}

]

使用sort函数可以做到这一点吗?在这种情况下会是什么情况?


小唯快跑啊
浏览 615回答 3
3回答

函数式编程

首先设置自定义优先级var codePriority = [ "GREEN", "BLUE", "RED" ];现在使用相同的排序方式arr.sort( function(a,b){    if ( a.code == b.code ) return a.value - b.value;   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) ; notice this line})演示版var arr = [    { code: "RED", value: 0},    { code: "BLUE", value: 0},    { code: "RED", value: 0},    { code: "GREEN", value: 0},    { code: "BLUE", value: 0},    { code: "RED", value: 0},    { code: "GREEN", value: 0},    { code: "BLUE", value: 0}];var codePriority = [ "GREEN", "BLUE", "RED" ];arr.sort( function(a,b){    if ( a.code == b.code ) return a.value - b.value;   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code )});console.log( arr );

波斯汪

您可以实现一个模式数组,并根据该模式数组中元素的索引进行排序。const a = ['GREEN', 'BLUE', 'RED'];const o = [{code:"RED",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0}];const r = o.slice().sort(({ code: q }, { code: w }) => a.indexOf(q) - a.indexOf(w));console.log(r);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript