-3

Below is an array object I would like to sort based on the first key value of each of the object in each of the array.

var beforeSort = [{
"James": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"William": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"Cindy": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"Apple": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"Timmy": "value",
"key": "value",
"key": "value",
"key": "value"
}];

The result that I want to achieve will be as below:

 var afterSort = [{
"Apple": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"Cindy": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"James": "value",
"key": "value",
"key": "value",
"key": "value"
},{
"Timmy": "value",
"key": "value",
"key": "value",
"key": "value"
},{
 "William": "value",
"key": "value",
"key": "value",
"key": "value"
}];

Is it technically possible?

Vincent1989
  • 1,593
  • 2
  • 13
  • 25
  • Many things are technically possible in programming. Often the first step is to figure out what sort of logic you're trying to implement, and second, to try writing some code – CertainPerformance Sep 09 '19 at 08:02
  • 1
    Possible duplicate of [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Etheryte Sep 09 '19 at 08:02

1 Answers1

0

You could take an array of common keys and filter the unknown key from all keys for sorting.

var commonKeys = ['a', 'b', 'c'];

array.sort((a, b) => {
    var keyA = Object.keys(a).filter(k => !commonKeys.includes(k))[0],
        keyB = Object.keys(b).filter(k => !commonKeys.includes(k))[0];

    return keyA.localeCompare(keyB);
})
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392