Reputation: 85
In AngularJS/Javascript i have an array of objects, these objects contain a date. I want to order these objects by date and add an attribute to the last object with a specific datetime. So if 2 objects have the same date i want to add the attribute to the one with the latest time. If there is only one object with one date i want to add the attribute to that object.
An example:
input: var arr = [
{A: {"Date": "2017-08-14T15:15:00"} B:{}}
{A: {"Date": "2017-08-14T16:15:00"} B:{}} //<--- Add attribute to this object
]
output: var arr = [
{A: {"Date": "2017-08-14T15:15:00"} B:{}}
{A: {"Date": "2017-08-14T16:15:00"} B:{} C:{"NewAttribute": "true"}}
]
How do i go about programming this? Originally i was thinking about using a for loop to compare all the objects with each other but i have no idea how to implement it.
Upvotes: 0
Views: 561
Reputation: 19070
You can first sort the array by Date using Array.prototype.sort() and than add the new attribute to the last element:
var arr = [
{A: {"Date": "2017-08-14T15:15:00"},B: {}},
{A: {"Date": "2017-08-16T16:15:00"},B: {}},
{A: {"Date": "2017-08-24T16:15:00"},B: {}},
{A: {"Date": "2017-08-24T16:15:00"},B: {}, C: {}}
],
alphabetArr = 'abcdefghijklmnopqrstuvwxyz'
.toLocaleUpperCase()
.split(''),
lastElementLength = 0;
// Sort the array
arr.sort(function (a, b) {
return new Date(b.A.date) - new Date(a.A.date);
});
// Get last element properties length
lastElementLength = Object.keys(arr[arr.length - 1]).length;
// Adds new attribute to last element with the proper name..
arr[arr.length - 1][alphabetArr[lastElementLength]] = {
"NewAttribute": "true"
};
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 7275
I hope I understood what you want:
var arr = [
{A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // won't get the new property
{A: {"Date": "2017-08-14T16:12:00"}, B:{}}, // will get the new property
{A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // will get the new property
{A: {"Date": "2017-08-14T16:14:00"}, B:{}}, // won't get the new property
{A: {"Date": "2017-08-14T16:14:00"}, B:{}} // will get the new property
];
// sort the array by date in descending order
var sorted = arr.sort(({A: { Date: d1 }}, {A: { Date: d2 }}) => new Date(d2).getTime() - new Date(d1).getTime());
// eventually add the new property
sorted.reduce((acc, o) => {
var date = o.A.Date;
if (acc !== date) {
// the date isn't equal to the date of the last item, so it's
// either the only item with that date
// or the first (in reversed order) item with that date
o.C = {"NewAttribute": "true"};
}
return date;
}, '');
// reverse the array
var result = sorted.slice().reverse();
console.log(result);
Upvotes: 1