I have an object array in js in the format of :
let arr = [{name:'bill',date:'2021-04-28T00:00:00'} , {name:'nick',date:'1999-12-02T00:00:00'},
{name:'john',date:'2021-04-28T00:00:00'} , {name:'patrick',date:'1999-12- 02T00:00:00'} ];
I want to create a new array from the one above that groups my objects into arrays where the date is the same . Example for above :
let grouped = [ [ {name:'bill','date':'2021-04-28T00:00:00'} ,
{name:'john','date':'2021-04-28T00:00:00'} ] ,
[
{name:'nick','date':'1999-12-02T00:00:00'},
{name:'patrick','date':'1999-12-02T00:00:00'}
]
];
My code below works for small datasets for like 2 , 4 objects but overrides data for more and creates duplicate arrays .
const groupByDates = (array)=>{
let grouped = [];
for(let i=0;i<array.length;i++){
grouped.push([array[i]]); //create [] and push element
for(let j=i+1;j<array.length;j++){
if(array[j].date===array[i].date){
grouped[i].push(array[j]); // if element has same date push to array
let index = array.indexOf(array[j].date);
array.splice(index,1); //remove item from array
}
}
//remove item from array after iteration
let index = array.indexOf(array[i].date);
array.splice(index,1);
}
return grouped;
}
let arr = [{name:'bill',date:'2021-04-28T00:00:00'}
, {name:'nick',date:'1999-12-02T00:00:00'},
{name:'john',date:'2021-04-28T00:00:00'} ,
{name:'patrick',date:'1999-12- 02T00:00:00'},
{name:'bruce',date:'1999-12- 02T00:00:00'} ,
{name:'mary',date:'1999-12- 02T00:00:00'} ,
];
let group = groupByDates(arr);
console.log(group);
I would appreciate your help