合并对象并返回压缩范围对象

时间:2017-02-27 22:05:24

标签: javascript javascript-objects

我正在解决这个问题:

  

编写一个函数mergeRanges(),它接受一系列会议时间   范围并返回一个浓缩范围数组(1 = 30分钟)

var arr =   [
    {startTime: 0,  endTime: 1},
    {startTime: 3,  endTime: 5},
    {startTime: 4,  endTime: 8},
    {startTime: 10, endTime: 12},
    {startTime: 9,  endTime: 10},
];

function result(arr){
  var finalResult = {};

  var c = arr.sort(function(a,b){ //First Sort
    return a.startTime - b.startTime;
  });

  var d = c.reduce(function(a,b){

   //Logic

   //check to see if start time lies between a[start] < b[startTime] < a[end]

    // If the startTime lies between a[startTime] to b[endTime] -> Merge them.

// if(a[startTime]< b[startTime] < b[endTime]){ //if start time lies between start and end.
    //   a[endTime] = b[endTime];
    //   delete b;
    // }

  });

}

result(arr);

我的解决方案如下:

$a = ['Name' => 'Last Name'];

function acc($acc,$k)use($a){ return $acc .= $k.":".$a[$k].",";}

$imploded = array_reduce(array_keys($a), "acc");

我无法理解如何使用reduce函数来交换逻辑。有人可以开导我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用reduce()和一个变量来存储endTime。

&#13;
&#13;
var input = [
    {startTime: 0,  endTime: 1}, 
    {startTime: 3,  endTime: 5}, 
    {startTime: 4,  endTime: 8},
    {startTime: 10, endTime: 12},
    {startTime: 9,  endTime: 10},
]

var c = 0;
var result = input.reduce(function(r, e, i) {
  //Check if c < startTime of current object in loop or if its first
  //element and if it is add it to r
  if (c < e.startTime || i == 0) {
    r.push(e)
  } else {
    //if not check if endTime of current object is > c 
    //(so you don't have problem at last object where endTime is smaller then some previous endTime) and change it
    //in r of last element that you added
    if (e.endTime > c) r[r.length - 1].endTime = e.endTime
  }
  //Always set c to current endTime
  c = e.endTime
  return r
}, [])

console.log(result)
&#13;
&#13;
&#13;