例如,這是輸入陣列:[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 中提供解決方案和解釋,將不勝感激。謝謝!
uj5u.com熱心網友回復:
腳本:
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)
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/467262.html
標籤:javascript 数组 排序 输出 团体
