是否能夠排列陣列形成連續序列 - JavaScript
我們需要編寫一個 JavaScript 函式,該函式接受一個數字陣列並檢查陣列元素是否可以重新排列以形成序列。
例如 −
如果陣列為 −
const arr = [3, 1, 4, 2, 5];
那麼輸出應該是 −
true
例子
以下是程式碼 −
const arr = [3, 1, 4, 2, 5];
const canBeConsecutive = (arr = []) => {
if(!arr.length){
return false;
};
const copy = arr.slice();
copy.sort((a, b) => a - b);
for(let i = copy[0], j = 0; j < copy.length; i++, j++){
if(copy[j] === i){
continue;
};
return false;
};
return true;
};
console.log(canBeConsecutive(arr));輸出
以下是控制檯中的輸出 −
true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP