8

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"}
]
3
  • So you have a order, which should be achieved and therefore you want to reorder your array? Commented Aug 24, 2016 at 12:09
  • I don't understand what you need to do, You want order arrayobject for Id? Commented Aug 24, 2016 at 12:09
  • @Pranav C Balan solved this problem, and he understood, please check. Also @Nenad Vracar has good way for solving this. My var order has order of ids from array objects. Commented Aug 26, 2016 at 8:31

3 Answers 3

13

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);

Sign up to request clarification or add additional context in comments.

2 Comments

What should the function passed return? A number value? A boolean value?
2

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)

Comments

0

I guess anything that involves sort can not be more efficient than an O(2n) solution. So i would like to do this job with two reduces as follows;

var arr = [{id: 1, name: "Matt"}, {id: 2, name: "Jack"}, {id: 3, name: "Morgan"}, {id: 4, name: "Bruce"}],
  order = [1,4,2,3],
    lut = order.reduce((t,e,i) => (t[e] = i,t),{}),
 result = arr.reduce((res,obj) => (res[lut[obj.id]] = obj, res) ,[]);
 console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.