1

I am trying to sorting object(key, value) values and printing in console. I know object keys sorting but i don't know values sorting. I tried bellow code to sort object values.

countries1 = {
  IN: ["India"],
  AE: ["United Arab Emirates"],
  AT: ["Austria"],
  SV: ["El Salvador"],
  SX: ["Sint Maarten (Dutch part)"],
  CH: ["Switzerland"],
  CI: ["Côte d'Ivoire"],
  SZ: ["Swaziland"],
  CG: ["Congo"]
};

var keys = Object.keys(countries1),
    i,
    len = keys.length,
    keys1 = [];
var objects = {};

for (var x = 0; x < len; x++) {
  var k = keys[x];
  var j = countries1[k][0];
  objects[k] = j;
}

console.log(objects);
Andreas
  • 21,535
  • 7
  • 47
  • 56

1 Answers1

0

You can't sort an object in JavaScript. If you have control over the object make it an array instead, it's easier to work with. Otherwise, convert it to an array and work with that.

e.g.

var countries1 = {
  IN: ["India"],
  AE: ["United Arab Emirates"],
  AT: ["Austria"],
  SV: ["El Salvador"],
  SX: ["Sint Maarten (Dutch part)"],
  CH: ["Switzerland"],
  CI: ["Côte d'Ivoire"],
  SZ: ["Swaziland"],
  CG: ["Congo"]
};

var sorted = Object
  .keys(countries1)
  .map(function(value, index) {
    return [countries1[value][0], value];
  })
  .sort();

console.log(sorted);

Why you can't sort an object better explained here: https://stackoverflow.com/a/1069705/1869996

Community
  • 1
  • 1
jolvera
  • 2,369
  • 1
  • 15
  • 15