根据条件lodash重新排序数组

时间:2016-10-13 07:21:29

标签: javascript functional-programming lodash

我有一个这样的集合:

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

我还有一个包含名称的变量:

var selfName = 'bar';

如何重新排列乐谱集合,使包含selfName的对象位于索引0处。预期结果:

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

我知道我可以通过以下方式实现:

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

有更好的方法吗?

3 个答案:

答案 0 :(得分:3)

Nina 提供的出色解决方案。但是,既然您想使用lodash,那么如果您愿意考虑,还有另一种替代解决方案。



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

var temp = _.partition(scores, function(score) { return score.name === selfName; });

var result = _.concat(...temp);
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用Array#sort对其进行排序,并将比较结果作为订单值进行排序。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

另一个有效的.sort。我认为逻辑表达式比Nina排序中使用的表达式更自然直观。

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

var selfName = 'bar';

scores.sort(({name:a}, {name:b}) => a === selfName || b === selfName);

console.log(scores);
&#13;
&#13;
&#13;