3

Ok, so I'm getting some data from a server like this: myVar = JSON.parse(xhttp.responseText). Now, my var looks something like:

{
    someData1234:{
        score: "5",
        loc: "NY"
    },

    someData4321:{
        score: "70",
        loc: "MH"
    },

    someData4123:{
        score: "43",
        loc: "NG"
    }
}

How can i sort through the object so it orders it by the score in an descending order? i tried other solutions but didn't seem to work correctly as i need the same object(or an array of objects) back but just re-ordered

kriskotoo BG
  • 194
  • 13
  • object cant be sortable.Array only have index to sorting – prasanth Mar 12 '19 at 04:19
  • 1
    There is no concept of "sort" in objects, because there is [no order guarantee in JavaScript object](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). – yqlim Mar 12 '19 at 04:30

5 Answers5

1

As already noted, JavaScript object property order is not guaranteed, so you will have to convert your data into an array of objects and then sort. Following example uses Object.entries and map to convert the initial object into an array, then sorts by parsing a numerical value from score in each object:

const obj = {
  someData1234: {score: "5", loc: "NY"},
  someData4321: {score: "70", loc: "MH"},
  someData4123: {score: "43", loc: "NG"}
};

let arr = Object.entries(obj).map(([k, v]) => ({[k]: v}));
let sorted = arr.sort((a, b) => {
  return parseInt(a[Object.keys(a)[0]].score) - parseInt(b[Object.keys(b)[0]].score);
});
console.log(sorted);
// [{"someData1234":{"score":"5","loc":"NY"}},{"someData4123":{"score":"43","loc":"NG"}},{"someData4321":{"score":"70","loc":"MH"}}]
benvc
  • 12,401
  • 3
  • 22
  • 45
  • seems like your code would work! cant test it right now but i will try it when i get home! thanks! – kriskotoo BG Mar 12 '19 at 20:53
  • your code does seem to work correctly! thanks but would it be too much to ask how can i make it sort in a descending order? i made a typo in the post... if its too much work don't bother. i will try to fix it! :) thanks again! – kriskotoo BG Mar 12 '19 at 21:18
  • @kriskotooBG - you can reverse the sort order by replacing the `return` line with `return parseInt(b[Object.keys(b)[0]].score) - parseInt(a[Object.keys(a)[0]].score);` - `a - b` sorts ascending, `b - a` sorts descending. – benvc Mar 13 '19 at 00:11
0
    var array = [{  
    "EmployeeName": "John",  
    "Experience": "12",  
    "Technology": "SharePoint"  
}, {  
    "EmployeeName": "Charles",  
    "Experience": "9",  
    "Technology": "ASP.NET"  
}, {  
    "EmployeeName": "Jo",  
    "Experience": "3",  
    "Technology": "JAVA"  
}, {  
    "EmployeeName": "Daine",  
    "Experience": "7",  
    "Technology": "Sql Server"  
}, {  
    "EmployeeName": "Zain",  
    "Experience": "6",  
    "Technology": "C#"  
}];  
//Comparer Function  
function GetSortOrder(prop) {  
    return function(a, b) {  
        if (a[prop] > b[prop]) {  
            return 1;  
        } else if (a[prop] < b[prop]) {  
            return -1;  
        }  
        return 0;  
    }  
}  

array.sort(GetSortOrder("EmployeeName")); //Pass the attribute to be sorted on  
document.write("Sorted Employee Names : ");  
for (var item in array) {  
    document.write("<br>" + array[item].EmployeeName);  
}  

array.sort(GetSortOrder("Technology")); //Pass the attribute to be sorted on  
document.write("<br><br> Sorted Technology Names : ");  
for (var item in array) {  
    document.write("<br>" + array[item].Technology);  
}  
vcongit
  • 9
  • 1
  • Hey! Thank you for the answer! but I'm getting kind of confused :( my question was about sorting a number not names ... Thanks Anyways! – kriskotoo BG Mar 12 '19 at 04:53
  • Please provide some explanation with your code in [answer](https://stackoverflow.com/help/how-to-answer). – Partho63 Mar 12 '19 at 04:53
0
  let something = {
    someData1234: {
      score: "5",
      loc: "NY"
    },

    someData4321: {
      score: "70",
      loc: "MH"
    },

    someData4123: {
      score: "43",
      loc: "NG"
    }
  };
  let someArray = [];
  let myArray = []
  Object.keys(something).map((som, ind) => {
    myArray.push(`${Object.values(Object.entries(something)[ind][1])[0]}` + ind);
  });
  myArray.sort((a, b) => {
    return a - b
  });
  console.log(myArray);

  for (let i = 0; i < myArray.length; i++) {
      let obj=Object.entries(something)[myArray[i].charAt(myArray[i].length-1)];
      console.log(obj);
      let key= obj[0];
      let value=obj[1];
    someArray.push({[key]:value})
  }
  let myOrderedObject;
  let obj;
  for(let i=0;i<someArray.length;i++){
     obj=someArray[i];
    console.log(obj);
     myOrderedObject={...myOrderedObject,...obj};
     console.log(myOrderedObject);
    console.log(i);
  }
  console.log('mY ordered Object ',myOrderedObject);

  console.log(someArray);

Hope it helps...

0

You could move the keys (like "someData1234") inside the objects (as the value of a "key" property), and put those objects in an array sorted by your liking: that way you have all information at hand:

const data = {someData1234:{score: "5",loc: "NY"},someData4321:{score: "70",loc: "MH"},someData4123:{score: "43",loc: "NG"}};

const result = Object.entries(data).map(([key, val]) => ({key, ...val}))
                     .sort((a,b) => a.score - b.score);
                     
console.log(result);
trincot
  • 211,288
  • 25
  • 175
  • 211
-3

const data = {
    someData1234:{
        score: "5",
        loc: "NY"
    },

    someData4321:{
        score: "70",
        loc: "MH"
    },

    someData4123:{
        score: "43",
        loc: "NG"
    }
};

// Use an Intl.Collator to construct a function that will sort number strings
const naturalSort = new Intl.Collator(undefined, { numeric: true }).compare;

const sortProperties = obj => Object.getOwnPropertyNames(obj) // Get the list of properties
  .sort((a, b) => naturalSort(obj[a].score, obj[b].score)) // Order based on the score
  .reduce( // Reduce the ordered properties to create a new object
    (result, prop) => {
      result[prop] = obj[prop];
      return result;
    }, {}
  );

console.log(sortProperties(data));
Adrian Brand
  • 15,308
  • 3
  • 24
  • 46