0

I have the following object:

Object { WK23: 12.52573059875292, WK22: 122.2625975869411, WK21:
78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2:
78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 }

Is it possible to sort it by keys, from WK1 to WK100 ? How to do this in JavaScript ?

Thanks in advance,

js_h_beg
  • 13
  • 1
  • please check this link https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key – Srinivas ML Jun 29 '17 at 09:30
  • Objects are, by definition, not ordered in Javascript. If you want it ordered you should convert it into an array – Lennholm Jun 29 '17 at 09:32
  • thanks guys for the answers. I'm the beginner of JS, will I able to back to object if i convert it into an array ? Do you have any example? thanks – js_h_beg Jun 29 '17 at 09:39
  • 1
    Possible duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – Arpit Solanki Jun 29 '17 at 10:35

3 Answers3

0

No, you can't. Object keys are not ordered. If you want to sort entries in an Object, you will have to convert it into an Array.

var obj = {"WK23": 12.52573059875292, "WK22": 122.2625975869411};
var result = Object.keys(obj).map(function(key) {
  return [key, obj[key]];
});

// the result Array can then be sorted...
// result = [["WK23": 12.52573059875292], ["WK22": 122.2625975869411]]

var sorted = result.sort(function(a,b){
    var num_a = parseInt(a[0].replace("WK", ""));
    var num_b = parseInt(b[0].replace("WK", ""));
    return num_a > num_b;
});
// sorted = [["WK22": 122.2625975869411], ["WK23": 12.52573059875292]]
Mathias Vonende
  • 1,352
  • 1
  • 18
  • 26
0

Try this , you can change order and assign to different object

var unordered={ WK23: 12.52573059875292, WK22: 122.2625975869411, WK21: 78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2: 78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 }

console.log(JSON.stringify(unordered));


const ordered = {};
Object.keys(unordered).sort(function(a,b){
var a=a.split("WK")[1];
var b=b.split("WK")[1];
return a-b
}).forEach(function(key) {
  ordered[key] = unordered[key];
});

console.log(JSON.stringify(ordered));
Srinivas ML
  • 687
  • 3
  • 11
0

here you go

const sample = { WK23: 12.52573059875292, WK22: 122.2625975869411, WK21:
78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2:
78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 };

const sorted = Object.keys(sample).sort().map(key => sample[key]);
Jee Mok
  • 4,537
  • 7
  • 35
  • 66