How to sort object array by it's key(ES6)

This is a very common problem which every developer face,

[
 { name: "josh", SortIndex: 28 },
 { name: "Nick", SortIndex: 22 },
 { name: "Iven", SortIndex: 26  }
].sort(function(obj1, obj2) {
 // Ascending: first age less than the previous
 return obj1.age - obj2.age;
});
 // Results:  
 // [
//   { name: "Nick", SortIndex: 22 }, 
//   { name: "Iven", SortIndex: 26  }, 
//   { name: "Josh", SortIndex: 28 }
// ]

No comments:

Post a Comment