Search code examples
javascriptarraysoverlapping

Check array overlapping in JavaScript


I have some arrays like [1,5], [3,6], [2,8],[19,13], [12,15]. When i pass two arrays in the function output will be [1,6], [2,19],[12,15]

i want to remove overlapping numbers from 2 arrays . like on fist and second array 5 and 3 will be overlap between 1 to 6.


Solution

  • I believe this is what you want (you get the min of the first array and the max of the second array):

    function removeOverlap(arr1, arr2) {
      if (arr1 === undefined) {
        return arr2;
      }
      
      if (arr2 === undefined) {
        return arr1;
      }
      
      return [Math.min.apply(null, arr1), Math.max.apply(null, arr2)];
    }
    
    // Sample:
    var myArrays = [[1,5], [3,6], [2,8], [19,13], [12,15]];
    
    for (var i = 0; i < myArrays.length; i = i + 2) {
      console.log(removeOverlap(myArrays[i], myArrays[i + 1]));
    }

    EDIT: answer with multiple parameters as you requested in your comment:

    We could use rest parameters in the answer below, but I will use the arguments object for compatibility with Internet Explorer. If this is not a requirement you can adapt the solution to use the first.

    function removeOverlap(arr1, arr2) {
      // Converting the arguments object to array:
      var argsArray = Array.prototype.slice.call(arguments);
    
      // Removing undefined:
      argsArray = argsArray.filter(function(el) {
        return el != undefined;
      });
    
      // Alternative (not compatible with Internet Explorer):
      //argsArray = argsArray.filter(el => el);
      
      // We're looking for the min and max numbers, let's merge the arrays
      // e.g. transform [[1, 5], [3, 6], [2, 8]] into [1, 5, 3, 6, 2, 8] 
      var merged = [].concat.apply([], argsArray);
    
      // Alternative, but it is not compatible with Internet Explorer:
      //var merged = Array.flat(argsArray);
      
      return [Math.min.apply(null, merged), Math.max.apply(null, merged)];
    }
    
    // Sample:
    var myArrays = [[1,5], [3,6], [2,8], [19,13], [12,15]];
    
    for (var i = 0; i < myArrays.length; i = i + 2) {
      console.log(removeOverlap(myArrays[i], myArrays[i + 1]));
    }
    
    console.log(removeOverlap(myArrays[0], myArrays[1], myArrays[2]));