-3

i have a multidimensional array in which there is value date and i want to sort it by this value below is array structure:

[
    ['01-Sep-2018', 'Some other Value'],
    ['20-Aug-2018', 'Some other Value'],
    ['21-Aug-2018', 'Some other Value'],
    ['22-Aug-2018', 'Some other Value'],
    ['23-Aug-2018', 'Some other Value']
]

I need output like this

[
    ['20-Aug-2018', 'Some other Value'],
    ['21-Aug-2018', 'Some other Value'],
    ['22-Aug-2018', 'Some other Value'],
    ['23-Aug-2018', 'Some other Value'],
    ['01-Sep-2018', 'Some other Value']
]
2

3 Answers 3

1

Below is the working code as your expectation.

compare_dates = function(date1,date2){

      d1= new Date(date1[0]);
      d2= new Date(date2[0]);
      if (d1>d2) return 1;
       else if (d1<d2)  return -1;
       else return 0;
    }
    var objs = [
        ['01-Sep-2018', 'Some other Value'],
        ['20-Aug-2018', 'Some other Value'],
        ['21-Aug-2018', 'Some other Value'],
        ['22-Aug-2018', 'Some other Value'],
        ['23-Aug-2018', 'Some other Value']
    ];

    objs.sort(compare_dates);

    console.log(objs);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.sort for this, the only complication is making the dates into something JS can parse. This can be done by replacing the - in the date with spaces, converting them to something like '20 Sep 2018' which is fine as an input to the Date constructor.

let array = [
    ['01-Sep-2018', 'Some other Value'],
    ['20-Aug-2018', 'Some other Value'],
    ['21-Aug-2018', 'Some other Value'],
    ['22-Aug-2018', 'Some other Value'],
    ['23-Aug-2018', 'Some other Value']
];
array.sort((a, b) => new Date(a[0].replace(/-/g, ' ')) - new Date(b[0].replace(/-/g, ' ')));
console.log(array);

Comments

0

You can do it with Array.prototype.sort and Array.prototype.map to extract the date values:

const data = [['01-Sep-2018', 'Some other Value'],['20-Aug-2018', 'Some other Value'],['21-Aug-2018', 'Some other Value'],['22-Aug-2018', 'Some other Value'],['23-Aug-2018', 'Some other Value']];

const sorted = data.sort((a,b) => {
    
    const [aD, bD] = [a,b].map(([d]) => new Date(d.replace(/-/gi,' ')))

    return aD - bD;

});

console.log(sorted);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.