是否能夠排列陣列形成連續序列 - 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

更新於: 16-Sep-2020

125 次瀏覽

開啟你的職業

完成課程後獲得認證

立即開始
廣告
© . All rights reserved.