我有一个对象数组,如下所示:
如何按第一个单词然后第二个单词对其排序。喜欢:
-Bulb: Vari-Fair
-Octopus: Agile
-Octopus: Energy Go
0: {id: 6, value: "Octopus: Agile"}
1: {id: 19, value: "EDF: EDF Economy 10 (SV)"}
2: {id: 20, value: "Octopus: Energy Go"}
3: {id: 21, value: "Igloo: Pioneer"}
4: {id: 22, value: "Scottish Power: Smart Green EV"}
5: {id: 23, value: "OVO: EV Everywhere"}
6: {id: 24, value: "E.ON: Fix and Drive"}
7: {id: 25, value: "Tonik: Charge EV"}
8: {id: 26, value: "Engie: EV Home"}
9: {id: 27, value: "Good Energy: EV Tariff"}
10: {id: 28, value: "Ecotricity: Fully Charged"}
11: {id: 29, value: "Bulb: Vari-Fair"}
12: {id: 30, value: "Green Energy UK: TIDE"}
13: {id: 32, value: "Our Power: Economy 10"}
答案 0 :(得分:1)
用':'分隔值,然后比较第一和第二:
const toSort = [
{id: 6, value: "Octopus: Agile"},
{id: 19, value: "EDF: EDF Economy 10 (SV)"},
{id: 20, value: "Octopus: Energy Go"},
{id: 21, value: "Igloo: Pioneer"},
{id: 22, value: "Scottish Power: Smart Green EV"},
{id: 23, value: "OVO: EV Everywhere"},
{id: 24, value: "E.ON: Fix and Drive"},
{id: 25, value: "Tonik: Charge EV"},
{id: 26, value: "Engie: EV Home"},
{id: 27, value: "Good Energy: EV Tariff"},
{id: 28, value: "Ecotricity: Fully Charged"},
{id: 29, value: "Bulb: Vari-Fair"},
{id: 30, value: "Green Energy UK: TIDE"},
{id: 32, value: "Our Power: Economy 10"}
]
const sorted = toSort.sort((a,b) => {
const f = a.value.split(': ');
const s = b.value.split(': ');
if(f[0] > s[0])
return 1;
if(f[0] < s[0])
return -1;
if(f[1] > s[1])
return 1;
return -1;
});
console.log(sorted)
答案 1 :(得分:1)
您可以执行以下操作:
var arr = [
{id: 6, value: "Octopus: Agile"},
{id: 19, value: "EDF: EDF Economy 10 (SV)"},
{id: 20, value: "Octopus: Energy Go"},
{id: 21, value: "Igloo: Pioneer"},
{id: 22, value: "Scottish Power: Smart Green EV"},
{id: 23, value: "OVO: EV Everywhere"},
{id: 24, value: "E.ON: Fix and Drive"},
{id: 25, value: "Tonik: Charge EV"},
{id: 26, value: "Engie: EV Home"},
{id: 27, value: "Good Energy: EV Tariff"},
{id: 28, value: "Ecotricity: Fully Charged"},
{id: 29, value: "Bulb: Vari-Fair"},
{id: 30, value: "Green Energy UK: TIDE"},
{id: 32, value: "Our Power: Economy 10"}
];
var result = arr.sort((a,b)=>a.value.localeCompare(b.value)); //utf8 support
console.log(result);