首页 > 解决方案 > 根据当前元素和先前元素之间的差异对排序数组进行分组

问题描述

我有一个按升序排序的数组:

const arr=[ 1, 2, 3, 5, 6, 7, 10, 12, 17, 18]

我必须对它进行分组,以便:

  1. 组内的元素相差1小于等于
  2. 每个组元素应该有多个元素被认为是有效的

基于上述条件,预期输出为:

const resultArr=[
  [1, 2, 3],
  [5, 6, 7],
  [17, 18]//each has more than one element
]

好的,此时我的大脑几乎停止了..

我尝试的是:

let prev = arr[0];
const resultArr = [prev];
for (let i = 1; i < arr.length; i++) {
  const curr = arr[i];

  if (curr - prev <= 1) {
    resultArr.push(curr);
  } else {
    resultArr.shift();
  }

  prev = curr;
}

非常感谢帮助!

reduce编辑:如果有没有功能的解决方案会很棒

标签: javascriptalgorithm

解决方案


您可以检查前任并将值添加到结果集的最后一个数组或检查下一个值是否有效,然后将新组添加到结果集中。

const
    array = [1, 2, 3, 5, 6, 7, 10, 12, 17, 18],
    result = array.reduce((result, value, index, array) => {
        if (array[index - 1] + 1 === value) result[result.length - 1].push(value);
        else if (value + 1 === array[index + 1]) result.push([value]);
        return result;
    }, []);    

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

一个带有经典循环的。

const
    array = [1, 2, 3, 5, 6, 7, 10, 12, 17, 18],
    result = [];


for (let index = 0; index < array.length; index++) {
    let value = array[index];

    if (array[index - 1] + 1 === value) {
        result[result.length - 1].push(value);
    } else if (value + 1 === array[index + 1]) {
        result.push([value]);
    }
}    

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读