0

This is my array

var obj = {
    1: "Principal",
    2: "Vice principal",
    3: "Co-Ordinator",
};

I need to sort this array to

var obj = {
    3: "Co-Ordinator",
    1: "Principal",
    2: "Vice principal",
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jebin
  • 39
  • 2

2 Answers2

0

You actually don't need jquery to solve this! Without jquery, your code will have the added benefit of being lighter.

In the code though, "obj" is an unstructured object, not an array, which means you can't sort it. If you wanted to be able to sort and actually use an array, "obj" would look like:

var obj = ["Principal", "Vice principal", "Co-Ordinator"]

Then, the indices are implied (principal corresponds to obj[0], vice principal to obj[1], etc.)

To sort alphabetically, you can then call obj.sort(). This will edit the original array. More here on the sort method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

0

You can make this array and apply sorting

var obj=[
    {id:1, title:"Principal"},
    {id:2, title:"Vice principal"},
    {id:3, title:"Co-Ordinator"},
];



var sortArray=(obj.sort((a,b)=>{
  let res=0
    if (a.title > b.title) {
    res= 1;
  } else if (a.title < b.title) {
    res= -1;
  } 
  return res;
}));

console.log(sortArray);


Otherwise 
var obj1 = ["Principal", "Vice principal", "Co-Ordinator"];
var obj2=obj1.sort();
console.log(obj2);