1

I have an array of objects structured like so (this is just example) and an array of id:

var array_objects=[
        {id:'a',value:1},
        {id:'b',value:2},
        {id:'c',value:2},
        {id:'d',value:3}
        ];

var array =['b','c','a','d'];

I wish to reorder array_objects the same way array is ordered. The order in the array can change each time. How to do this?

2
  • what sort of order is this? Commented May 11, 2015 at 14:14
  • You could foreach loop through array, referencing array_objects to create a new, sorted, array of objects Commented May 11, 2015 at 14:17

3 Answers 3

3

A simple solution:

array_objects.sort(function(a,b){
  return array.indexOf(a.id)-array.indexOf(b.id)
})

If you have a very big array and you want something really fast, here's a variant not calling indexOf:

var m = array.reduce(function(r,k,i){ return r[k]=i,r },{});
array_objects.sort(function(a,b){ return m[a.id]-m[b.id] });
Sign up to request clarification or add additional context in comments.

Comments

0

Easiest to generate a new array.

var arr2 = [], i;

for (i = 0; i < array.length; ++i)
    arr2[array.indexOf(array_objects[i].id)] = array_objects[i];

If it's important to use the same reference, you can do some magic with splice

var i;
for (i = 0; i < array.length; ++i)
    array_objects[array.indexOf(array_objects[i].id) + array.length] = array_objects[i];
array_objects.splice(0, array.length);

Comments

-1

I think this quite simple, try this:

array_objects.sort(function(a,b){
  return (a.id) > (b.id)
});

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.