【问题标题】:lodash - Move object to first place in array?lodash - 将对象移动到数组的第一位?
【发布时间】:2017-11-11 00:32:11
【问题描述】:

我有一个对象数组,类型为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'}
];

这是我的尝试: https://jsfiddle.net/zg6js8af/

如何让类型vegetable 成为数组中的第一项,而不管其当前索引如何?

【问题讨论】:

    标签: arrays lodash


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      为什么在不需要时使用 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));
      

      【讨论】:

      • 感谢您展示了另一种方法,赞成 :) 我已经在很多地方使用 lodash,老实说,我更喜欢它简洁的语法;即使最终目标相同:)
      • 为什么要重新发明轮子?
      • array.push,在 2018 年不是一个好的解决方案,imo。最好使用展开语法,arr = [...arr, 'new item']
      【解决方案3】:

      您可以通过type 在desc 方向订购:

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

      或使用partition

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

      【讨论】:

      • 谢谢,但我试图根据vegetable 的实际值=== 让它工作,所以它很灵活:)
      • 再次感谢,但我选择了_.sortBy,因为它是单一方法:)
      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2016-05-31
      • 2019-10-27
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      相关资源
      最近更新 更多