1

Convert Array of List into my Own Order

Current Output:

[
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", }
]

Convert this into

[
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }
]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392

3 Answers3

0

You could take an object for getting th right order and sort by the property which describes the order.

var data = [{ key: "DG Power Output", value: "6.00", unit: "kWh" }, { key: "DG Run Time", value: "5999999952", unit: "minutes" }, { key: "Fuel Level (Before)", value: "8.00", unit: "liters" }],
    order = { "Fuel Level (Before)": 1, "DG Run Time": 2, "DG Power Output": 3 };

data.sort(({ key: a }, {  key: b }) => order[a] - order[b]);

console.log(data);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

The most basic I would go would be by accessing the index, let's say

var a = [
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", }
]

Then,

var b = [a[2], a[1], a[0]];

This would give the output you want but it's very risky and error-prone.

Prajil Shrestha
  • 124
  • 1
  • 9
0

I'm not entirely sure what criteria you want to use to sort this array, but the general approach is to write a function that compares two elements and returns a number less than 0 for the first element to come first, 0 if they are equal, and a number greater than 0 for the second element to come first. You can then pass this function to Array.prototype.sort like this for descending order:

const sorter = (a, b) => {
    if (a.key == b.key) return 0; // leave elements in place
    if (a.key > b.key) return -1; // a should come before b for descending order
    return 1; // b should come before a for descending order
};
const arr = [
    { "key": "DG Power Output", "value": "6.00", "unit": "kWh", },
    { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", },
    { "key": "Fuel Level (Before)", "value": "8.00", "unit": "liters", }
];
console.log(arr.sort(sorter));
awarrier99
  • 3,628
  • 1
  • 12
  • 19