繁体   English   中英

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

[英]How can i check similar entries in an array and according to similar entries merge the values using 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" }
]

我想要的是,如果太阳星期四的时间相同,它将变成

[
  {"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"}
]

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

谢谢..!

您可以执行以下操作:

 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); 

试试这个提示

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
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM