【问题标题】:Grouping array of objects (collection) by adjacent integer property按相邻整数属性对对象数组(集合)进行分组
【发布时间】:2018-09-17 13:42:48
【问题描述】:

我试图通过属性int 对对象数组进行分组,以便获得一个嵌套数组并将每个项目分组到下一个值为n + 1 的位置。假设起始数组的顺序正确。

const value = [{int: 1}, {int: 2}, {int: 3}, {int: 15}, {int: 16}, {int: 21}]
const result = [
  [{int: 1}, {int: 2}, {int: 3}],
  [{int: 15}, {int: 16}],
  [{int: 21}],
]

【问题讨论】:

  • 请添加您的尝试。

标签: javascript arrays node.js object lodash


【解决方案1】:

使用Array.reduce() 迭代每个int,根据最后一个子数组的存在以及当前和最后一项之间的差值,决定是添加到当前子数组还是添加新子数组:

const value = [{int: 1}, {int: 2}, {int: 3}, {int: 15}, {int: 16}, {int: 21}]
const result = value.reduce((r, o) => {
  const last = r[r.length - 1];
  
  if(last && last[last.length - 1].int + 1 === o.int) last.push(o);
  else r.push([o]);
  
  return r;
}, []);

console.log(result);

【讨论】:

    【解决方案2】:

    const {each, last} = _
    
    function groupByIncrementingProp (collection, prop = 'key') {
      const results = []
      var bundle = []
      each(collection, (obj, key) => {
        if (!bundle.length || (obj[prop] - 1) !== last(bundle)[prop]) {
          bundle = []
          bundle.push(obj)
        } else if (obj[prop] - 1 === last(bundle)[prop]) {
          bundle.push(obj)
        }
        if (!collection[key + 1] || obj[prop] + 1 !== collection[key + 1][prop]) {
          results.push(bundle)
        }
      })
      return results
    }
    
    const value = [{key: 1}, {key: 2}, {key: 3}, {key: 15}, {key: 16}, {key: 21}]
    
    console.log(groupByIncrementingProp(value))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>

    【讨论】:

      【解决方案3】:

      也许一个简单的 for 循环就可以做到:

       const result = [];
       let previous = value[0], acc = [value[0]];
      
       for(const current of value.slice(1)) {
         if(current.int === previous.int + 1) {
           acc.push(current);
         } else {
           result.push(acc);
           acc = [current];
         }
         previous = current;
       }
       result.push(acc);
      

      【讨论】:

        猜你喜欢
        • 2023-02-07
        • 2015-12-31
        • 2021-11-25
        • 1970-01-01
        • 2014-11-28
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        相关资源
        最近更新 更多