检查两个数组是否可以形成序列-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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短