按相邻整数属性对对象(集合)数组进行分组

时间:2018-04-07 19:36:31

标签: javascript arrays node.js object lodash

我正在尝试通过属性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}],
]

3 个答案:

答案 0 :(得分:0)

为每个int迭代Array.reduce()决定是否添加到当前子数组或添加新子数组,根据最后一个子数组的存在,以及当前和最后一项之间的增量:

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

答案 1 :(得分:0)

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>

答案 2 :(得分:0)

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

autoencoder = TRUE