1

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!

3
  • Why Adam then Dave, how did you sort that out? Commented Nov 25, 2013 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 Commented Nov 25, 2013 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. Commented Nov 25, 2013 at 18:41

1 Answer 1

3

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;
});
Sign up to request clarification or add additional context in comments.

Comments

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.