eggman eggman - 7 months ago 16
Javascript Question

Rearrange index of array to match other array

I have two arrays containing the same elements but in different order, like this:

var arr1 = [{name: 'Bob', age: 24}, {name: 'Mary',age: 45}, {random: props}];
var arr2 = [{name: 'Mary', age:45 }, {name: 'Bob',24}, {other: randomProps}];


In this case of course a simple reverse() would do the trick but it might be an array with 10 objects in a random order.

Since both arrays always contains some common properties (
name
) I should be able to rearrange one array to match the other based on
name
.

Any tips on how to go about this?

Answer

Maybe something like this then? But this assumes that each object in the array has the name property.

var arr1 = [{name: 'Bob', age: 24}, {name: 'Mary',age: 45}, {random: props}]; 
var arr2 = [{name: 'Mary', age:45 }, {name: 'Bob',24}, {other: randomProps}];

function sortArray(arr) {
 arr.sort(function(a, b) {
   return a.name > b.name;
 }); 
}

sortArray(arr1);
sortArray(arr2);