Ntiyiso Rikhotso
Ntiyiso Rikhotso

Reputation: 720

How do I go about sorting this kind of object?

Here is my object

{
    "1MON": "1",
    "1TUE": "1",
    "2TUE": "2",
    "3WED": "3",
    "6FRI": "6"
}

I have been trying to search hoping to get an answer but no luck.

I want to use the values to sort it

The expected output is

{
    "1MON": "1",
    "1TUE": "1",
    "2TUE": "2",
    "3WED": "3"
}

and then later on, I want to loop on it to remove the values and create a string like 1MON1TUE2TUE3WED6FRI. The reason why i am doing this is that i want to add HTML classes like class="class-1MON1TUE2TUE3WED6FRI" and when i want to remove 1 slot in that class i will use myClassAsString.replace(/1TUE/g, "") please help me!

Upvotes: 0

Views: 72

Answers (2)

toastal
toastal

Reputation: 1073

Object keys in JavaScript aren’t sorted & you can never expect them to be. You need to convert to an Array for that behavior.

const x = { "1MON": "2", "1TUE": "1", "2TUE": "2", "3WED": "3", "6FRI": "6" }

Object.entries(x)
  .sort(([,a], [,b]) => a > b)
  .map(([y]) => y)
  .join("")
//=> "1MON1TUE12TUE3WED6FRI"

Upvotes: 1

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

For Sorting you can try like this.

  1. Get All the properties of the Object using Object.keys(obj);
  2. Sort Items in the array by using the Comparer callback function for strings.

var obj = {"1MON":"1","1TUE":"1","2TUE":"2","3WED":"3","6FRI":"6"};
var allProperties = Object.keys(obj);
var sortedResult = allProperties.sort( (first, second) => first.localeCompare(second) );

console.log(sortedResult)

Upvotes: 0

Related Questions