我有两个数组:
- values:包含所有值的数组
- mainValues:带有 mainValues 的列表,这些值已经存在于数组值中,但必须排序。即 mainValues 应该是数组值中的第一个值
我这样解决了这个问题,但我不确定这是否是最佳实践:
var values = ['bla', 'x', 'y', 'z', 'two', 'one', 'three'];
var mainValues = ['one', 'two', 'three'];
_.forEach(mainValues.reverse(), function(val) {
var index = _.indexOf(values, val);
values.splice(index, 1);
values.unshift(val);
});
console.log(values); // => ["one", "two", "three", "bla", "x", "y", "z"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>