Sorting an array of objects by date

10

Well I'm with an array of objects and I need to sort the closest to today to far away from today. For example today is 24/11/2015 ai I have in my array the dates:

30/11/2015 
27/11/2015
25/11/2015
30/11/2015 

In case the result I'm needing is that these dates come like this:

25/11/2015
27/11/2015
30/11/2015
30/11/2015

Within my array I can date, name, and phone.

I tried to use sort() inside this array but it did not work. I actually do not quite understand why sort()

    
asked by anonymous 24.11.2015 / 14:08

4 answers

9

I've adapted this answer to your need, you can create your own function and pass it as a parameter of the sort function.

See Running.

    var objeto = [ 
    { data : new Date('11-30-2015'), nome: 'Marconi', telefone:'32486745425'},
    { data : new Date('11-31-2015'), nome: 'Marcos', telefone:'32486745425'},
    { data : new Date('11-25-2015'), nome: 'B', telefone:'32486745425'},
    { data : new Date('11-27-2015'), nome: 'Testes', telefone:'32486745425'},
];
 			
function compare(a,b) {
  return a.data < b.data;
}

console.log(objeto.sort(compare));
    
24.11.2015 / 14:22
3
  

I performed some tests with the function and was performing the sort order   wrong because the date was string. to work properly, you must   use a variable of type Date

You can use sort itself, it accepts as an optional parameter a function, see an example.

var teste = [
        { nome: "pedro", data: new Date('11-30-2015') },
    	{ nome :"joao", data: new Date('12-01-2015') },
        { nome: "maria", data: new Date('10-05-2015') }
    ];

function ordemDecrescente(a, b) {
    return a.data < b.data;
}

function ordemCrescente(a, b) {
    return a.data > b.data;
}
    
teste.sort(ordemDecrescente);

console.log(teste);
    
24.11.2015 / 14:19
1

I used this once:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);
    return $t1 - $t2;
}    
usort($array, 'date_compare');

usort - Sorts an array by the values using a user-defined comparison function.

The function takes two records of array at a time and compares, if equal returns zero; if greater, positive number; and if smaller, negative number. The usort uses this result to sort the array.

Retired from SOEn: link

    
24.11.2015 / 14:13
0

var teste = [{
    nome: "pedro",
    data: new Date('11-30-2018')
  },
  {
    nome: "joao",
    data: new Date('12-01-2018')
  },
  {
    nome: "maria",
    data: new Date('10-05-2018')
  }
];

function ordemDecrescente(a, b) {
  return a.data - b.data;
}

function ordemCrescente(a, b) {
  return b.data - a.data;
}

teste.sort(ordemCrescente);

console.log(teste);

var points = [40, 100, 1, 5, 25, 10];
console.log(points.sort(function(a, b) {
  return b - a
}));
    
26.12.2018 / 20:30