Get the keys of the object into an array and sort it

Hi in this post we are going to see how convert the keys of the object into an array and sort it.

In this case we have our object:

const myData = {
  X50: {
    description: "This is the description for X50",
    isActive: true,
  },
  X100: {
    description: "This is the description for X100",
    isActive: false,
  },
  X70: {
    description: "This is the description for X70",
    isActive: true,
  },
};

console.log("myData --->", myData);

Result:

Ok, our next step is get the keys of our object and insert this key into an array format:

In this case we can use the Object.keys – this returns an array of keys.

const myData = {
  X50: {
    description: "This is the description for X50",
    isActive: true,
  },
  X100: {
    description: "This is the description for X100",
    isActive: false,
  },
  X70: {
    description: "This is the description for X70",
    isActive: true,
  },
};

// Object.keys(myData) returns an array of keys
const myDataArray = Object.keys(myData);

console.log("myDataArray --->", myDataArray);

Result:

Then we need to order this Array, but look that in this case we can’t use just the .sort() because we have strings with numbers in each position of the array, so in this case we can use the .localCompare() method inside the .sort() method:

const myData = {
  X50: {
    description: "This is the description for X50",
    isActive: true,
  },
  X100: {
    description: "This is the description for X100",
    isActive: false,
  },
  X70: {
    description: "This is the description for X70",
    isActive: true,
  },
};

let myDataArray = Object.keys(myData);

const ordered = myDataArray.sort((a, b) =>
  a.localeCompare(b, navigator.languages[0] || navigator.language, {
    numeric: true,
    ignorePunctuation: true,
  })
);

console.log("ordered ====>", ordered);

Result:

Nice, and now if we want to sort the array in reverse order we can change the a.localCompare(b….) to b.localCompare(a…) check this code:

const myData = {
  X50: {
    description: "This is the description for X50",
    isActive: true,
  },
  X100: {
    description: "This is the description for X100",
    isActive: false,
  },
  X70: {
    description: "This is the description for X70",
    isActive: true,
  },
};

let myDataArray = Object.keys(myData);

const ordered = myDataArray.sort((a, b) =>
  b.localeCompare(a, navigator.languages[0] || navigator.language, {
    numeric: true,
    ignorePunctuation: true,
  })
);

console.log("ordered ====>", ordered);

Result:

By Cristina Rojas.