1

Let's say I have the following array:

[
    {
       "key":"Certified?",
       "value":"Yes"
    },
    {
       "key":"Language",
       "value":"EN"
    },
    {
       "key":"Training-Place",
       "value":"City"
    }
 ]

I want to sort it in a specific order of Language, Certified?, Training-Place, how can I achive that? Preferably I would be able to define the sorting like:

["Language", "Certified?", "Training-Place"]

Thank you very much, any help is appreciated.

nimrod
  • 5,595
  • 29
  • 85
  • 149

2 Answers2

3

You can simply use Arrays.sort() and use a order array to sort the array in the order specified by the order array.

Try the following:

var arr = [ { "key":"Certified?", "value":"Yes" }, { "key":"Language", "value":"EN" }, { "key":"Training-Place", "value":"City" }, { "key":"Training-Place", "value":"aaa" }, { "key":"Language", "value":"bbb" }];

var order = ["Language", "Certified?", "Training-Place"];
 
 arr.sort((a,b)=> order.indexOf(a.key) - order.indexOf(b.key));
 
 console.log(arr);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
1

Create an array which will contain the order. Now loop over this array and from the main array filter out the object which matches with the name

let arrayToSort = [{
    "key": "Certified?",
    "value": "Yes"
  },
  {
    "key": "Language",
    "value": "EN"
  },
  {
    "key": "Training-Place",
    "value": "City"
  }
]


let sortOrder = ["Language", "Certified?", "Training-Place"]
let customSortArray = [];
sortOrder.forEach(function(item) {
  customSortArray.push(
    arrayToSort.filter(function(items) {
      return item === items.key
    })[0])
})


console.log(customSortArray)
brk
  • 48,835
  • 10
  • 56
  • 78