OK so given this input (other properties have been stripped for brevity):

var names = [{
    name: 'Michael'
}, {
    name: 'Liam'
}, {
    name: 'Jake'
}, {
    name: 'Dave'
}, {
    name: 'Adam'
}];

I'd like to sort them by another array's indices, and if they aren't in that array, sort alphabetically.

var list = ['Jake', 'Michael', 'Liam'];

Giving me an output of:

Jake, Michael, Liam, Adam, Dave

I've tried using lo-dash but it's not quite right:

names = _.sortBy(names, 'name');
names = _.sortBy(names, function(name) {
    var index = _.indexOf(list, name.name);
    return (index === -1) ? -index : 0;
});

as the output is:

Jake, Liam, Michael, Adam, Dave

Any help would be really appreciated!

share|improve this question
    
Why Adam then Dave, how did you sort that out? – elclanrs Nov 25 '13 at 0:05
    
i hope you are aware that there is a function called sort() within javascript and it can sort your array alphabetically ! so the problem now is to move your elements into another array ? list.sort(); will output Adam, Dave,Jake, Michael, Liam – ProllyGeek Nov 25 '13 at 0:17
    
@elclanrs - "if they aren't in that array, sort alphabetically", so in other terms the whole array is sorted alphabetically but those three keys come first if that makes sense. Yes, I am aware of sort() although I was already using lodash in the project so it doesn't matter to me to use a native method over the (in my opinion, neater) lodash one. – Ben Nov 25 '13 at 18:41
up vote 2 down vote accepted

You are close. return (index === -1) ? -index : 0; is the problem.

Following your approach, it should look like this:

names = _.sortBy(names, 'name')

var listLength = list.length;

_.sortBy(names, function(name) {
    var index = _.indexOf(list, name.name);
    // If the name is not in `list`, put it at the end
    // (`listLength` is greater than any index in the `list`).
    // Otherwise, return the `index` so the order matches the list.
    return (index === -1) ? listLength : index;
});
share|improve this answer
    
Works great. Thanks for your explanation. :-) – Ben Nov 25 '13 at 18:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.