
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
Get Intersection Between Two Ranges in JavaScript
Suppose, we have two arrays of numbers that represents two ranges like these −
const arr1 = [2, 5]; const arr2 = [4, 7];
We are required to write a JavaScript function that takes in two such arrays.
The function should then create a new array of range, that is the intersection of both the input ranges and return that range.
Therefore, the output for the above input should look like this −
const output = [4, 5];
Example
The code for this will be −
const arr1 = [2, 5]; const arr2 = [4, 7]; const findRangeIntersection = (arr1 = [], arr2 = []) => { const [el11, el12] = arr1; const [el21, el22] = arr2; const leftLimit = Math.max(el11, el21); const rightLimit = Math.min(el12, el22); return [leftLimit, rightLimit]; }; console.log(findRangeIntersection(arr1, arr2));
Output
And the output in the console will be −
[ 4, 5 ]
Advertisements