0

I want to sort object keys in ASC .My keys is string and number so try with sort is not solve .

//sorting number function
function sortNum(a,b) {
    return a - b;
}
let obj = {key10:10,key2:2,key5:5,key1:1};
let ordered = {};
Object.keys(obj).sort().forEach(function(key,v){
    ordered[key] = v;
});
console.log(ordered); //{key1: 1, key10: 10, key2: 2, key5: 5}
//try with sort number function
//Object.keys(obj).sort(sortNum).forEach(function(key){
//ordered[key] = obj[key];
//});
//console.log(ordered); -> {key10: 10, key2: 2, key5: 5, key1: 1}

Expected => {key1: 1, key2: 2, key5: 5, key10: 10}

Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52

4 Answers4

1

Since they all have the same start (key), sort by comparing the numbers.

I've stored it as an array that you can just use to access the original object.

let obj = {key10:10,key2:2,key5:5,key1:1};
var ordered = Object.keys(obj).sort( (a,b) => {
  let numA = a.match(/\d+/);
  let numB = b.match(/\d+/);
  return +numA - +numB;
});
console.log(ordered);
A. L
  • 11,695
  • 23
  • 85
  • 163
0

Try with Array#sort sorting with ASC order and Array#reduce used for return with object .Finally /(\d+)/ used for find the numbers in the key

let obj = {key10:10,key2:2,key5:5,key1:1};
var ordered = Object.keys(obj).sort((a,b)=>{
       return  parseInt(a.match(/(\d+)/)) < parseInt(b.match(/(\d+)/)) ? -1 : parseInt(a.match(/(\d+)/)) > parseInt(b.match(/(\d+)/)) ? 1 :0;
}).reduce((a,b) => (a[b]=obj[b] ,a),{})
console.log(ordered);
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

I used the Array.prototype methods to map and reduce your collection in your sorted collection. Read the comments and let me know if you need more clarification!

let obj = {
  key10: 10,
  key2: 2,
  key5: 5,
  key1: 1
};
let ordered = (Object
  // creates an array of keys
  .keys(obj)
  // map each key into a tuples of {key, value} objects
  .map(key => ({
    key,
    value: obj[key]
  }))
  // sort those objects by the value
  .sort((a, b) => a.value - b.value)
  // then reduce back into another object
  .reduce((ordered, {key, value}) => {
    ordered[key] = value;
    return ordered;
  }, {})
);


console.log(ordered);
Rico Kahler
  • 17,616
  • 11
  • 59
  • 85
0

You could use both parts of the string, nonnumerical, sort by string and the numerical part, sort by number with a regular expression.

let obj = { key10: 10, key2: 2, key5: 5, key1: 1, foo1000: 1000, foo0: 0, foo20: 20 },
    keys = Object.keys(obj);

keys.sort(function (a, b) {
    function parts(s) { return s.match(/\D+|\d+/g); }
    var aa = parts(a),
        bb = parts(b);
    return aa[0].localeCompare(bb[0]) || aa[1] - bb[1];
});

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