脚本:
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)
}