
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Two Arrays Can Form a Sequence in JavaScript
We are required to write a JavaScript function that takes in two arrays of numbers.
And the function should return true if the two arrays upon combining and shuffling can form a consecutive sequence, false otherwise.
For example − If the arrays are −
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
Then the output should be true.
Example
Following is the code −
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));
Output
Following is the output in the console −
true
Advertisements