Reputation: 1016
I currently have this function which sort an array alphabetically.
function compare(a,b) {
if (a.subtitle < b.subtitle)
return -1;
if (a.subtitle > b.subtitle)
return 1;
return 0;
}
I need a similar function that sorts the array by another array. I tried writing it myself but i couldn't get my head around it so i ended up with nothing.
Example:
I need array1 to be sorted depending on where that item is in array2.
Array1 = ['quick','fox','the','brown'];
Array2 = ['the','quick','brown','fox'];
There is probably an easy answer that i am not seeing.
Edit:
Also any items that are in array1 that aren't in array 2 can just be tacked onto the end in no particular order or alphabetically whatever is easier.
Upvotes: 1
Views: 100
Reputation: 53
I ran across the need to do the same thing today, this was my solution:
var arr = [".", 5359, 1, 2, 3, 4, 6, 9, 15];
var priorities = [3, '.', 1, 4, 15, 9, 2, 6];
var resultArr = arr.filter( function(arrElement) { return priorities.indexOf(arrElement) >= 0 })
.sort( function (a,b) { return priorities.indexOf(a) - priorities.indexOf(b) })
.concat( arr.filter( function(arrElement) { return priorities.indexOf(arrElement) < 0})
);
console.log(resultArr.join(""));
console: 3.14159265359
jsfiddle based on @rps's answer
Basically, it picks out the elements that we have a preferred order for, sorts those, then appends the elements that we had no order preference for. As a bonus (at least for my use case), the sorting is non-destructive to the order of arr
.
I'm not sure if this is better or worse, but I know I loathe for
loops. :)
Upvotes: 0
Reputation: 794
Try this:
function compare(a,b, compareArray) {
if ((compareArray.indexOf(a) != -1 && compareArray.indexOf(a) < compareArray.indexOf(b))
|| compareArray.indexOf(b) == -1)
return -1;
if ((compareArray.indexOf(a) > compareArray.indexOf(b))
|| compareArray.indexOf(a) == -1)
return 1;
return 0;
}
Upvotes: 2
Reputation:
var Array1 = ['quick', 'fox', 'the', 'brown', 'abc']; //the array to be sorted
var Array2 = ['the', 'quick', 'brown', 'fox'];
var sortedAry = [];
for (var i = 0; i < Array2.length; i++) {
var index = Array1.indexOf(Array2[i]);
if (index !== -1) {
console.log(index);
sortedAry.push(Array2[i]);
Array1.splice(index, 1);
}
}
for (var j = 0; j < Array1.length; j++) {
sortedAry.push(Array1[j]);
}
console.log(sortedAry);
Upvotes: 0