0

I have an array of objects that I would like to convert to a new array with different structure by removing duplicate elements based on an attribute of the array. For example, this array would be filtered by date property:

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

==> would become :

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

So, how can i do this using js(ES5) or angularjs

1

1 Answer 1

0

You can use array reduce and findIndex.findIndex will be used to check if there exist a date ,if it exist it will return a index. Use this index to find the element in the new array and there just update the times array

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, it's working :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.