Javascript:根据属性从具有重复元素的数组构造数组

时间:2018-08-08 17:24:26

标签: javascript arrays

我有一个对象数组,我想通过基于数组属性删除重复元素来转换为具有不同结构的新数组。 例如,此数组将按date属性进行过滤:

var arrayWithDuplicates = [
   {
       "date":"02/08/2018", 
       "startTime": "09:00",
       "endTime": "12:00"
  },
  {
       "date":"02/08/2018", 
       "startTime": "14:00",
       "endTime": "17:00"
  }
];

==>将变为:

  var newArray = [
  {
      "date":"02/08/2018", 
      "times": [
       {
           "startTime": "09:00",
            "endTime": "12:00"
       }, {
            "startTime": "14:00",
            "endTime": "17:00"
       }
       ]             
 ];

所以,我该如何使用js(ES5)或angularjs

1 个答案:

答案 0 :(得分:0)

您可以使用数组reduce和findIndexfindIndex将用于检查是否存在日期,如果存在,它将返回索引。使用该索引在新数组中找到元素,然后在那里更新times数组

var arrayWithDuplicates = [{
    "date": "02/08/2018",
    "startTime": "09:00",
    "endTime": "12:00"
  },
  {
    "date": "02/08/2018",
    "startTime": "14:00",
    "endTime": "17:00"
  }
];
let newArray = arrayWithDuplicates.reduce(function(acc,curr){
   let checkIfExist = acc.findIndex(function(item){
       return item.date === curr.date
   });
  if(checkIfExist ===-1){
   let obj = {};
   obj.date = curr.date;
   obj.times = [{
    startTime:curr.startTime,
    endTime:curr.endTime
   }]
    acc.push(obj);
  }
  else{
   acc[checkIfExist].times.push({
    startTime:curr.startTime,
    endTime:curr.endTime
   })
  
  }
  return acc;
},[]);

console.log(newArray)