【问题标题】:Javascript group the numbers from an array with series of consecutive numbersJavascript将数组中的数字与一系列连续数字分组
【发布时间】:2017-12-20 13:10:56
【问题描述】:

例如,给定一个排序的整数数组

a = [0,1,2,5,6,9];

我想确定范围

[
    [0,1,2],
    [5,6],
    [9]
]

到目前为止,我已经尝试了双/三循环,但它嵌套在非常讨厌的代码中。 也许这个问题可以使用递归或其他聪明的技巧来解决?


附加示例:

输入

b = [0,1,5,6,7,9];

输出

[
    [0,1],
    [5,6,7],
    [9]
]

【问题讨论】:

  • 所以,第一个数组应该包含 3,接下来是 2,最后一个应该只有 1 个元素。对吗?
  • 对于这个例子是,但通常不是。它应该分割出 int 范围
  • 如果a = [0,1,2,5,6,9, 12];,输出会是什么?
  • @Salman 不,如果数字按顺序排列,它会创建一个数组,即 1,2,3 - 7,8,9
  • 所以你想把一个排序好的数组拆分成其他连续数字的数组?

标签: javascript arrays


【解决方案1】:

使用Array#reduce 进行迭代,当最后一个数字不等于新数字 - 1 时,添加另一个子数组。将当前数字添加到最后一个子数组中:

const a = [0,1,2,5,6,9];

const result = a.reduce((r, n) => {
  const lastSubArray = r[r.length - 1];
  
  if(!lastSubArray || lastSubArray[lastSubArray.length - 1] !== n - 1) {
    r.push([]);
  } 
  
  r[r.length - 1].push(n);
  
  return r;  
}, []);

console.log(result);

【讨论】:

  • 我爱你,谢谢你的好解决方案!
  • 幸福地结婚生子,但不客气:)
【解决方案2】:

像@OriDrori 这样的Array.reduce 做得很好。

另一个想法是使用简单的 for 循环和切片。

function groupArray(a) {
  const ret = [];
  if (!a.length) return ret;
  let ixf = 0;
  for (let ixc = 1; ixc < a.length; ixc += 1) {
    if (a[ixc] !== a[ixc-1] + 1) {
      ret.push(a.slice(ixf, ixc));
      ixf = ixc;  
    }
  }
  ret.push(a.slice(ixf, a.length));
  return ret;
}

console.log(JSON.stringify(groupArray([0,1,2,5,6,9])));

【讨论】:

    【解决方案3】:

    您可以使用普通的 for 循环并检查当前数字和前一个数字之间的差异

    var a = [0, 1, 2, 5, 6, 7, 9];
    // this variable will contain arrays
    let finalArray = [];
    // Create a recursive function
    function checkPrevNextNumRec(array) {
      let tempArr = [];
      // if the array contaon only 1 element then push it in finalArray and
      // return it
      if (array.length === 1) {
        finalArray.push(array);
        return
      }
      // otherside check the difference between current & previous number
      for (let i = 1; i < array.length; i++) {
        if (array[i] - array[i - 1] === 1) {
          // if current & previous number is 1,0 respectively 
          // then 0 will be pushed
          tempArr.push(array[i - 1]);
        } else {
          // if current & previous number is 5,2 respectively 
          // then 2 will be pushed
          tempArr.push(array[i - 1])
          // create a an array and recall the same function
          // example from [0, 1, 2, 5, 6, 9] after removing 0,1,2 it 
          // will create a new array [5,6,9]
          let newArr = array.splice(i);
          finalArray.push(tempArr);
          checkPrevNextNumRec(newArr)
        }
        // for last element if it is not consecutive of
        // previous number 
        if (i === array.length - 1) {
          tempArr.push(array[i]);
          finalArray.push(tempArr)
        }
      }
    
    }
    checkPrevNextNumRec(a)
    console.log(finalArray)

    【讨论】:

      【解决方案4】:

      这是我想出的:

      const a = [0,1,2,5,6,9];
      
      const solution = (arr, expected = 0, group = []) => 
          arr.reduce((acc, c, i) => 
              ((c === expected 
                  ? (group.push(c), expected++)
                  : (acc.push(group), group = [c], expected=++c)), 
                (i === arr.length-1 && acc.push(group)), 
                acc), []);
      
      console.log(solution(a));

      【讨论】:

        猜你喜欢
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-15
        • 1970-01-01
        • 2011-02-07
        • 1970-01-01
        • 2019-04-08
        相关资源
        最近更新 更多