lodash - 将对象移动到数组的第一个位置?

18

我有一个对象数组,其中包含类型为fruit/vegetable两种。

对于类型为vegetable的那个,我想让它成为数组中的第一项,但我不确定如何使用lodash实现。

var items = [
    {'type': 'fruit', 'name': 'apple'},
    {'type': 'fruit', 'name': 'banana'},
    {'type': 'vegetable', 'name': 'brocolli'}, // how to make this first item
    {'type': 'fruit', 'name': 'cantaloupe'}
];

这里有我的fiddle尝试: https://jsfiddle.net/zg6js8af/

我怎样才能让类型为 vegetable 的项目成为数组的第一项,而不管它目前的索引是多少?

4个回答

30
使用lodash _.sortBy。如果类型是蔬菜,它将首先进行排序,否则排在第二位。

let items = [
  {type: 'fruit', name: 'apple'},
  {type: 'fruit', name: 'banana'},
  {type: 'vegetable', name: 'brocolli'},
  {type: 'fruit', name: 'cantaloupe'},
];

let sortedItems = _.sortBy(items, ({type}) => type === 'vegetable' ? 0 : 1);

console.log(sortedItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


这是另一种不使用lodash的解决方案。

function sortBy(array, fn) {
  return array.map(v => [fn(v), v]).sort(([a], [b]) => a - b).map(v => v[1]);
}

let items = [
  {type: 'fruit', name: 'apple'},
  {type: 'fruit', name: 'banana'},
  {type: 'vegetable', name: 'brocolli'},
  {type: 'fruit', name: 'cantaloupe'},
];

let sortedItems = sortBy(items, ({type}) => type === 'vegetable' ? 0 : 1);

console.log(sortedItems);


3
为什么在不需要它的情况下使用lodash(而且可以使用单个reduce编写函数式代码)?
var items = [
  {'type': 'fruit', 'name': 'apple'},
  {'type': 'fruit', 'name': 'banana'},
  {'type': 'vegetable', 'name': 'brocolli'},
  {'type': 'fruit', 'name': 'cantaloupe'}
];

var final = items.reduce(function(arr,v) {
  if (v.type === 'vegetable') return [v].concat(arr)
  arr.push(v)
  return arr
},[]);
alert(JSON.stringify(final));

4
谢谢您提供一个替代方法,已点赞 :) 实话实说,我已经在很多地方使用lodash,并且喜欢它干净的语法;即使最终目标相同 :) - Wonka
为什么要重复造轮子呢? - Alex
array.push在2018年不是一个好的解决方案,我认为最好使用展开语法,arr = [...arr, '新项目']。 - Alex

2

您可以通过按type字段进行倒序排序来完成:

var res = _.orderBy(items, ['type'], ['desc']);

或者使用partition
var res = _.chain(items)
    .partition({type: 'vegetable'})
    .flatten()
    .value();

谢谢,但我试图让它基于vegetable的实际值===工作,所以它是灵活的 :) - Wonka
谢谢你的建议,但我选择了_.sortBy,因为它只是一个方法 :) - Wonka

0
这是一个使用 ES6 中的数组 reduce 函数的简洁解决方案:
const items = [
  { type: 'fruit', name: 'apple' },
  { type: 'fruit', name: 'banana' },
  { type: 'vegetable', name: 'brocolli' },
  { type: 'fruit', name: 'cantaloupe' }
]

const final = items.reduce(
  (accumulator, current) =>
    current.type === 'vegetable'
      ? [current, ...accumulator]
      : [...accumulator, current],
  []
)
console.log(final)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接