如何按 n 和递减整数的数量 (n-1) 对数组进行分组?输出为数组总数

How do you group an array by n and the number of decreasing integers (n-1)? With the output to be the total number of arrays

例如,这是输入数组:[2, 1, 4, 4, 3]

从这个数组中,n-1个模式将从左到右建立。

此输出将是数字 7,因为分组后存在以下单独的数组:

[2] [1] [4] [4] [3] - 1 组 (n)

[4, 3] - 1组(n-1)

[2, 1] - 1组(n-1)

输出:7(数组)

这是我到目前为止的开始,但看起来我只是将所有内容汇总在一起。

let numbers = [2, 1, 4, 4, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue;
});

console.log(sum);

如果在JavaScript中提供解决方案和解释,我们将不胜感激。谢谢!

脚本:

function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  // remove duplicates
  let unique = [...new Set(numbers)];
  // get length of unique array, then add to the length of filtered unique array where it also contains n-1
  console.log(unique.length + unique.filter(number => numbers.includes(number - 1)).length);
}

获取唯一元素的数量,然后将其添加到过滤后的唯一数组的长度,其中还包含 n-1.

输出:

如果你想获取数组:

function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  let unique = [...new Set(numbers)];
  var arrays = [];
  unique.forEach(number => {
    arrays.push([number]); 
    if(numbers.includes(number - 1))
      arrays.push([number, number-1])
  });

  console.log(arrays.length)
  console.log(arrays)
}