0

I have a large dataset I need to sort by a preset order. It's simple enough to get the array sorted, but the problem is having the values not in the sort order moving to the bottom instead of the top. Here's my code...

var order = ["value1", "value2", "value3"];
var result = ["value4", "value2","value1","value1", "value3"].sort(function(a,b) {
 var aIndex = order.indexOf(a),
 bIndex = order.indexOf(b);
 if (aIndex > bIndex)
 return 1;
 if (aIndex < bIndex)
 return -1;
 return 0;
});

...and the fiddle.

I can't figure out how to have a condition that considers something not in the order array to be a lower sort order. I've tried adding if (aIndex < 0 || bIndex < 0) return -1; before the existing conditions, but this will be potentially incorrect of one of the two is in the sort order.

asked May 22, 2014 at 14:09

1 Answer 1

1

You could try setting aIndex and bIndex to the length of the order array when they are -1, thus pushing them to the end of the array.

Example in this fiddle: http://jsfiddle.net/a3LfP/1/

answered May 22, 2014 at 14:16
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.