在JavaScript中找到两个数组的连续性
我们需要编写一个包含两个数字数组的JavaScript函数。如果两个数组在组合和改组后可以形成连续序列,则函数应返回true,否则返回false。
例如:如果数组是-
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
然后输出应为true。
因此,让我们为该函数编写代码-
示例
为此的代码将是-
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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短