检查两个数组是否可以形成一个序列 - JavaScript
我们需要编写一个 JavaScript 函数,该函数采用两个数字数组。
并且该函数应该返回 true,如果这两个数组在组合和洗牌后可以形成连续的序列,否则返回 false。
例如 − 如果数组是 −
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
那么输出应该是 true。
举例
以下是代码 −
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP