Reputation: 111
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?
Upvotes: 1
Views: 58
Reputation: 5564
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);
Upvotes: 1
Reputation: 184
I think you can scan the arranged array and search elements in the second array and put them in a new array.
new_array;
foreach(element in array_ordered)
{
temp = search(element[name], array_unordered);
if(temp != null)
new_array.add(temp);
}
Upvotes: 0