Removing already listed intervals in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

JavaScript function that takes in a 2-D array, arr, as the first and the only argument.

Each subarray of our input array is an array of exactly two numbers, specifying a time interval.

Our function should remove all intervals that are covered by another interval in the array arr. Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. Our function should finally return the number of remaining intervals in the array.

For example, if the input to the function is −

const arr = [
[2, 5],
[5, 7],
[3, 9]
];

Then the output should be −

const output = 2;

Output Explanation:

Interval [5, 7] is covered by [3, 9], therefore it is removed.

Example

The code for this will be −

Live Demo

const arr = [
[2, 5],
[5, 7],
[3, 9]
];
const removeCovered = (arr = []) => {
arr.sort(([a, b], [c, d]) => (a === c ? d - b : a - c));
let last = arr[0];
let count = arr.length;
for(let i = 1; i < arr.length; i++){
const [a, b] = last;
const [c, d] = arr[i];
if(c >= a && d <= b){
count -= 1;
}else{
last = arr[i];
};
};
return count;
};
console.log(removeCovered(arr));

Output

And the output in the console will be −

2
Published on 07-Apr-2021 07:27:14