Ben
Ben

Reputation: 10146

Sort an object on indices of an array in JavaScript?

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!

Upvotes: 1

Views: 2814

Answers (1)

go-oleg
go-oleg

Reputation: 19480

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;
});

Upvotes: 3

Related Questions