0

I have several inputs, let's say here are two inputs like the following:

const first = 50;
const second = [[14, 16], [28, 30]];

How can i get the following result:

expected result = [[0, 13], [14, 16], [17, 27], [28, 30], [31, 50]];

Now my code is like this and still confused to arrange the correct logic, thank you

const first = 50;
const second = [[14, 16], [28, 30]].flat(1);

let result = [];
for(let i = 0; i < second.length; i++) {
   let temp = second[i];
   if (i === 0) {
     result.push([i, temp - 1]);
   }
   result.push([i+temp, temp+2]);
}

console.log(result); // output [[0, 13], [14, 16], [17, 18], [30, 30], [33, 32]]

DEMO

Shbdn
  • 17
  • 5

1 Answers1

0

When iterating over the array of arrays. push the array being iterated over itself to the result. Examine its second value to determine where the next iteration should start at.

const first = 50;
const second = [[14, 16], [28, 30]];

const result = [];
let start = 0;
while (second.length) {
  const secondItem = second.shift();
  result.push([start, secondItem[0] - 1]);
  result.push(secondItem);
  start = secondItem[1] + 1;
}
if (start < first) {
  result.push([start, first]);
}
console.log(result);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320