如何检查数组中的类似条目,并根据类似条目使用javascript合并值?

时间:2018-03-08 04:49:24

标签: javascript

我有一组数据,如

[
  { "day": "Mon", "time": "11:00AM – 10:00PM" }, 
  { "day": "Tue", "time": "11:00AM – 10:00PM" }, 
  { "day": "Wed", "time": "11:00AM – 10:00PM" }, 
  { "day": "Thu", "time": "11:00AM – 10:00PM" }, 
  { "day": "Fri", "time": "11:00AM – 11:00PM" }, 
  { "day": "Sat", "time": "11:00AM – 11:00PM" }, 
  { "day": "Sun", "time": "11:00AM – 10:00PM" }
]

我想要的是,如果 Sun Thu 的时间相同,它将成为

[
  {"day":"Sun-Thu", "time":"11:00AM – 10:00PM"},
  {"day":"Fri-Sat","time":"11:00AM – 11:00PM"}
]

我试过了

for (var i = 0; i < jsonData.length; i++) {
  for (var j = i + 1; j < jsonData.length;) {
    if (jsonData[i].time == jsonData[j].time) {

      var hour = {
        day: jsonData[i].day + "-" + jsonData[j].day,
        time: jsonData[i].time
      }
      arr.push(hour);
      jsonData.splice(i, 1);
      jsonData.splice(j - 1, 1);
    } else {
      j++;
    }
  }
}

但正在制作

[
  {"day":"Sun","time":"11:00AM – 10:00PM"},
  {"day":"Mon-Tue","time":"11:00AM – 10:00PM"},
  {"day":"Wed-Thu","time":"11:00AM – 10:00PM"},
  {"day":"Fri-Sat","time":"11:00AM – 11:00PM"}
]

请帮助我如何获得预期的数据。

感谢..!

2 个答案:

答案 0 :(得分:1)

您可以这样做:

var arr = [{ "day": "Mon", "time": "11:00AM – 10:00PM" },{ "day": "Tue", "time": "11:00AM – 10:00PM" },{ "day": "Wed", "time": "11:00AM – 10:00PM" },{ "day": "Thu", "time": "11:00AM – 10:00PM" },{ "day": "Fri", "time": "11:00AM – 11:00PM" },{ "day": "Sat", "time": "11:00AM – 11:00PM" },{ "day": "Sun", "time": "11:00AM – 10:00PM" }];

// Set "Sun" as first day of the week
arr.unshift(arr.pop());

var result = arr.reduce((a, c) => {
  // check if the time of the last range is the same as the time of the current element.
  let same = a.length && a[a.length - 1].time === c.time && a[a.length - 1];
  if(same){
     // replace the last day of the range (if any) with the day of the current element
     same.day = same.day.replace(/\-.*$/, "") + "-" + c.day;
  }else{
    // add the current element to the result array because its time is not the same as the time of the last element.
    a.push(c)
  }
  return a;
}, []);

console.log(result);

答案 1 :(得分:-2)

尝试此提示

var a = [
  { "day": "Mon", "time": "11:00AM – 10:00PM" }, 
  { "day": "Tue", "time": "11:00AM – 10:00PM" }, 
  { "day": "Wed", "time": "11:00AM – 10:00PM" }, 
  { "day": "Thu", "time": "11:00AM – 10:00PM" }, 
  { "day": "Fri", "time": "11:00AM – 11:00PM" }, 
  { "day": "Sat", "time": "11:00AM – 11:00PM" }, 
  { "day": "Sun", "time": "11:00AM – 10:00PM" }
]

var b = a.filter(function(rm){return rm.time == "11:00AM – 11:00PM"})

var t = {}

for(var i =0;i<b.length;i++){
if(t[b[i].time]){
t[b[i].time] = t[b[i].time]+"-"+ b[i].day
}else{
t[b[i].time] = b[i].day
}
}