
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Checking if two arrays can form a sequence - 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
- Related Articles
- Can array form consecutive sequence - JavaScript
- Checking for the similarity of two 2-D arrays in JavaScript
- Checking for ascending arrays in JavaScript
- Checking if a string can be made palindrome in JavaScript
- Checking if change can be provided in JavaScript
- Checking for centrally peaked arrays in JavaScript
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Checking for special type of Arrays in JavaScript
- Checking for squared similarly of arrays in JavaScript
- Checking the equality of array elements (sequence dependent) in JavaScript
- Check if the elements of the array can be rearranged to form a sequence of numbers or not in JavaScript
- Checking if an array is sorted lexicographically in reference to some scrambled alphabet sequence in JavaScript
- Can we convert two arrays into one JavaScript object?
- Form a sequence out of an array in JavaScript
- Count Triplets That Can Form Two Arrays of Equal XOR in C++

Advertisements