I have two arrays in Javascript coming from Php. I merge these arrays into one array.
All of arrays' elements has created_at value (Laravel). I want to sort these values by created_at
Problem: Regardless of their date. First array's elements never take place in behind of those of second array
Example: B has latest date. But even so, C (comes from second array) takes place after B.
The problem is although I merged these two arrays into one array. Javascript still thinks "there are two arrays. I should sort first array's elements then those of second array."
What do I do is :
history.push(...response.data[0]); // first array's values
history.push(...response.data[1]); // second array's values
history.sort((a, b) => {
return a.created_at - b.created_at;
});
so, history like
[
// Comes from first array
{
name: 'A',
created_at: '08/09/2021'
},
// Comes from first array
{
name: 'B',
created_at: '15/09/2021'
},
// This third element comes from second array.
{
name: 'C',
created_at: '08/09/2021'
}
]
I expect this result:
new sorted history:
{
name: 'A',
created_at: '08/09/2021'
},
{
name: 'C',
created_at: '08/09/2021'
},
{
name: 'B',
created_at: '15/09/2021'
}
But Javascript initially sorts first array's element. After, sort second array's element then what comes out is:
{
name: 'A',
created_at: '08/09/2021'
},
{
name: 'B',
created_at: '15/09/2021'
},
{
name: 'C',
created_at: '08/09/2021'
},
history.sort(). Why are you expecting them to be reordered?