When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at
value (from Laravel), and I want to sort these elements by their created_at
values.
The issue arises when the elements of the first array never get placed behind those of the second array, regardless of their dates. For example, if B has the latest date, C from the second array still appears after B.
The problem stems from the fact that even though I merge the two arrays, JavaScript treats them as separate entities, leading it to try sorting the first array's elements before the second array's.
To address this, my approach is:
history.push(...response.data[0]); // values from the first array
history.push(...response.data[1]); // values from the second array
history.sort((a, b) => {
return a.created_at - b.created_at;
});
As a result, the updated history should look like this:
[
// Elements from the first array
{
name: 'A',
created_at: '08/09/2021'
},
{
name: 'B',
created_at: '15/09/2021'
},
// The third element is from the second array.
{
name: 'C',
created_at: '08/09/2021'
}
]
The expected sorted history should be:
new sorted history:
{
name: 'A',
created_at: '08/09/2021'
},
{
name: 'C',
created_at: '08/09/2021'
},
{
name: 'B',
created_at: '15/09/2021'
}
However, due to JavaScript initially sorting the elements of the first array followed by the second array, the actual output appears as:
{
name: 'A',
created_at: '08/09/2021'
},
{
name: 'B',
created_at: '15/09/2021'
},
{
name: 'C',
created_at: '08/09/2021'
}