-3

I have an array of objects like the one below:

enter image description here

How can I order them by first word then the second. Like:

-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"}
AnXD
  • 255
  • 1
  • 4
  • 15

2 Answers2

1

split the value by ': ' and compare first and second:

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)
wang
  • 1,660
  • 9
  • 20
1

You can do as follow:

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);
protoproto
  • 2,081
  • 1
  • 13
  • 13