Reputation: 4366
I am trying to sort this array
by timestamp values. I want to sort them in ascending order and if any of them have an indefinite property, place it at the end. I currently have the error Cannot read property 'first_release_date' of undefined. How to solve this?
var array =
[
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"first_release_date": 1083542400,
"name": "Item 1"
},
{
"id": 113242,
"name": "Item 2"
},
{
"id": 25076,
"first_release_date": 1540512000,
"name": "Item 3"
},
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"name": "Item 4"
},
{
"id": 9245,
"first_release_date": 1292976000,
"name": "Item 5"
}
];
Object.keys(array).forEach((key) => {
console.log(`Before: ${array[key].name}`)
});
array.sort((a,b) => a.array.first_release_date > b.array.first_release_date);
Object.keys(array).forEach((key) => {
console.log(`After: ${array[key].name}`)
});
Upvotes: 1
Views: 852
Reputation: 8589
You are almost there. Only need to provide a default value for when there's no date. Also, sort requires you to return a number, at the moment you return a boolean, which will be cast to 0 or 1. Which will break the sort for the cases you want to return a negative number.
var array =
[
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"first_release_date": 1083542400,
"name": "Item 1"
},
{
"id": 113242,
"name": "Item 2"
},
{
"id": 25076,
"first_release_date": 1540512000,
"name": "Item 3"
},
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"name": "Item 4"
},
{
"id": 9245,
"first_release_date": 1292976000,
"name": "Item 5"
}
];
Object.values(array).forEach((val) => {
var d = new Date(val.first_release_date*1000).getFullYear();
console.log(`Before: ${ val.name} ${d }`)
});
array.sort((a,b) => ( a.first_release_date || Number.POSITIVE_INFINITY ) - ( b.first_release_date || Number.POSITIVE_INFINITY ));
Object.values(array).forEach((val) => {
var d = new Date(val.first_release_date*1000).getFullYear();
console.log(`After: ${ val.name} ${d }`)
});
var reverse = JSON.parse( JSON.stringify( array ));
reverse.sort((a,b) => ( b.first_release_date || Number.NEGATIVE_INFINITY ) - ( a.first_release_date || Number.NEGATIVE_INFINITY ));
console.log( reverse );
Upvotes: 5