4

Suppose I have two arrays, like this:

var SortedArray = [25, 123, 2464, 112, 54, 51, 347, 4572, 634];
var ArrayToSort = [634, 25, 51, 123];

SortedArray is an array that contains the order of many elements. ArrayToSort contains just some of the elements of SortedArray and every element in ArrayToSort is certain to also be in SortedArray.

What's the best way to sort ArrayToSort so that the elements in that array appear in the same order as SortedArray and get this result:

ArrayToSort = [25, 123, 51, 634];

2 Answers 2

6

Try this:

ArrayToSort.sort(function(x, y) {
    return SortedArray.indexOf(x) - SortedArray.indexOf(y);
});

Demonstration

Note: using this method, if an element does not appear in SortedArray, it will be placed before all other elements that are found in SortedArray.

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

1 Comment

Wow, all this in one line!! Nice answer!
4

You could do this as an alternative to sorting as you already have a sorted array of elements.

var sortedArray = [25, 123, 2464, 112, 54, 51, 347, 4572, 634],
    arrayToSort = [634, 25, 51, 123],
    sorted = sortedArray.filter(function (num) {
        return arrayToSort.indexOf(num) !== -1;
    });

console.log(sorted);

Output

[25, 123, 51, 634] 

On jsFiddle

1 Comment

+1 I was about to add something like this as an alternative when your answer popped up.

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.