2017-02-02 51 views
1

我发现了类似的问题,但已批准的答案对我的问题无效。使用javascript合并数组中具有区间属性的重叠对象

我有一个输入:的范围对象数组每个包含:

  • start:整数,的范围开始,
  • end:整数,该范围的末尾。

输出应为:

非重叠范围的对象覆盖相同的范围(或多个)从最小开始排列到最大启动输入的数组。两个范围不重叠的,如果:

  • range1.start <= range2.start,和
  • range1.end >= range2.start

输入:

[ 
    { start: 8, end: 10 }, 
    { start: 5, end: 7 }, 
    { start: 9, end: 12 }, 
    { start: 2, end: 6 }, 
] 

输出:

[ 
    { start: 2, end: 7 }, 
    { start: 8, end: 12 } 
] 

正如我所提到的,我尝试过在Web上应用解决方案来合并重叠间隔,但他们没有完成这项工作。

谢谢。

回答

0

您可以按startend排序数组,并重复排序的数组,并检查范围是否重叠。

var data = [{ start: 8, end: 10 }, { start: 5, end: 7 }, { start: 9, end: 12 }, { start: 2, end: 6 }], 
 
    result = data 
 
     .sort(function (a, b) { return a.start - b.start || a.end - b.end; }) 
 
     .reduce(function (r, a) { 
 
      var last = r[r.length - 1] || []; 
 
      if (last.start <= a.start && a.start <= last.end) { 
 
       if (last.end < a.end) { 
 
        last.end = a.end; 
 
       } 
 
       return r; 
 
      } 
 
      return r.concat(a); 
 
     }, []); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

var ranges = [ 
 
    { start: 8, end: 10 }, 
 
    { start: 5, end: 7 }, 
 
    { start: 9, end: 12 }, 
 
    { start: 2, end: 6 } 
 
]; 
 

 

 
function merge(ranges) { 
 
    // first, sort the ranges 
 
    ranges.sort((a, b) => a.start - b.start); 
 
    
 
    // take two ranges, and merges them together 
 
    var mergeFn = (a, b) => ({start: Math.min(a.start, b.start), end: Math.max(a.end, b.end)}); 
 
    
 
    // check if two ranges overlap 
 
    var overlapFn = (a, b) => (b.start <= a.end); 
 
    
 
    // make current the first item of the array (start the array from 1 to not check the first item against itself) 
 
    var current = ranges[0]; 
 
    var result = []; 
 
    for(var i = 1; i < ranges.length; i++) { 
 
    if(overlapFn(current, ranges[i])) // if the current range overlapping with this range 
 
     current = mergeFn(current, ranges[i]); // merge them into the current range 
 
    else { // if not 
 
     result.push(current); // add the current accumulated range as result 
 
     current = ranges[i]; // start accumulating another one from this range 
 
    } 
 
    } 
 
    result.push(current); // add the last result 
 

 
    return result; 
 
} 
 

 
console.log(merge(ranges));

+0

谢谢你,易卜拉欣。出于某种原因,您提供的代码不适用于我(a和b无法被我正在处理的页面上的验证程序识别),但我在此看到您的代码正常工作。我用Nina的代码,它的工作。谢谢。 –

+0

不客气!也许你的浏览器不支持**箭头函数**(假设你的代码是用于浏览器的)。 –

相关问题