Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript doesn't sort correctly an array including two arrays' values

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'
 },

like image 324
Ali Gökmen Kudaş Avatar asked Aug 15 '26 14:08

Ali Gökmen Kudaş


1 Answers

You can array#concat both your array and use Schwartzian transform to sort your array by converting the created_at to YYYY-MM-DD format which could be sorted lexicographically.

const arr1 = [{name: 'A', created_at: '08/09/2021'}],
      arr2 = [{name: 'B', created_at: '15/09/2021'}, {name: 'C', created_at: '08/09/2021'}],
      result = arr1.concat(arr2)
                   .map(o => [o.created_at.replace(/(..)\/(..)\/(....)/, '$3-$2-$1'), o])
                   .sort((a,b) => a[0].localeCompare(b[0]))
                   .map(([,o]) => o);
console.log(result)
like image 59
Hassan Imam Avatar answered Aug 18 '26 05:08

Hassan Imam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!