jgr0 jgr0 - 1 month ago 8
Javascript Question

Reorder array based on condition lodash

I have a collection like so:

var scores = [{
name: foo,
score: 34
}, {
name: bar,
score: 23
}, {
name: baz,
score: 99
}]


I also have a variable containing a name:

var selfName = 'bar';


How can I rearrange scores collection such that the object containing selfName is at index 0. Expected result :

[{
name: bar,
score: 23
}, {
name: foo,
score: 34
}, {
name: baz,
score: 99
}]


I know I can do it by:

var isSelfName = (selfName, score) => {
var _name = selfName;
return (score) => {
return score.name === selfName;
}
};
var result = _.filter(scores, isSelfName(selfName));
result.push(_.reject(scores, isSelfName(selfName)));
result = _.flatten(result);
console.log('result:', result);


Is there a better way of doing it?

Answer

You could sort it with Array#sort and a comparison result as order value.

var scores = [{ name: 'foo', score: 34 }, { name: 'bar', score: 23 }, { name: 'baz', score: 99 }],
    selfName = 'bar';

scores.sort(function (a, b) {
    return (a.name !== selfName) - (b.name !== selfName);
});

console.log(scores);

Comments