Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set order to array of object in javascript

I need to find a simplest way for setting order to array of objects. For example, there is an array:

var array = [
    {id: 1, name: "Matt"},
    {id: 2, name: "Jack"},
    {id: 3, name: "Morgan"},
    {id: 4, name: "Bruce"}
];

and I have provided

var order = [1,4,2,3];

which refers to object id property of array items.

Now I need to reorder array so it should be like:

var array = [
    {id: 1, name: "Matt"},
    {id: 4, name: "Bruce"},
    {id: 2, name: "Jack"},
    {id: 3, name: "Morgan"}
]
like image 379
Jarosław Wlazło Avatar asked Aug 24 '16 12:08

Jarosław Wlazło


2 Answers

Use Array#sort method for sorting and inside custom sort function use Array#indexOf method to get index.

var array = [{
  id: 1,
  name: "Matt"
}, {
  id: 2,
  name: "Jack"
}, {
  id: 3,
  name: "Morgan"
}, {
  id: 4,
  name: "Bruce"
}];

var order = [1, 4, 2, 3];


array.sort(function(a, b) {
  // sort based on the index in order array
  return order.indexOf(a.id) - order.indexOf(b.id);
})

console.log(array);
like image 60
Pranav C Balan Avatar answered Sep 17 '22 11:09

Pranav C Balan


You can also use reduce() on [1,4,2,3] array to return object where keys will be elements and values will be index of each element and then sort by that object.

var array = [
  {id: 1, name: "Matt"},
  {id: 2, name: "Jack"},
  {id: 3, name: "Morgan"},
  {id: 4, name: "Bruce"}
];

var s =  [1,4,2,3].reduce((r, e, i) => {return r[e] = i, r}, {});
var result = array.sort(function(a, b) {
  return s[a.id] - s[b.id];
});
console.log(result)
like image 34
Nenad Vracar Avatar answered Sep 17 '22 11:09

Nenad Vracar