Javascript : Construct array from an array with duplicate elements by property [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Javascript : Construct array from an array with duplicate elements by property [duplicate]



This question already has an answer here:



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



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





Fairly basic groupBy approach jsfiddle.net/nbrhtpof/8
– charlietfl
Aug 8 at 17:53




1 Answer
1



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


findIndex


findIndex


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)





Thank you for your answer, it's working :)
– Khadija_
Aug 9 at 9:25

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS