在 JavaScript 中查詢兩個陣列的連續性
我們需要編寫一個 JavaScript 函式,該函式接受兩個數字陣列。並且該函式應當在可以結合並洗牌的情況下返回真,否則返回假。
例如:如果陣列是 -
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
那麼輸出應該是真。
因此,讓我們編寫此函式的程式碼 -
示例
程式碼將是 -
const arr1 = [4, 6, 2, 9, 3];
const arr2 = [1, 5, 8, 7];
const canFormSequence = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
if(combined.length < 2){
return true;
};
combined.sort((a, b) => a-b);
const commonDifference = combined[0] - combined[1];
for(let i = 1; i < combined.length-1; i++){
if(combined[i] - combined[i+1] === commonDifference){
continue;
};
return false;
};
return true;
};
console.log(canFormSequence(arr1, arr2));輸出
控制檯中的輸出將是 -
true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP