Get intersection between two ranges in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
raja
Published on 21-Nov-2020 09:34:09
Advertisements