Arrangement of dates by fixes in Javascript

0

I have an arrangement as follows [{ first name:"---", date: "05-06-2019" }, { first name:"---", date: "08-06-2019" }, { first name:"---", date: "10-01-2019" } ] I would like to order the arrangement of the form from the closest date to the farthest one, how could I do it ???

    
asked by fernando quinteros gutierrez 03.01.2019 в 21:47
source

1 answer

1

Use the function sort for fixes, this performs the ordering on the same instance of the array and you can pass a function as a parameter that tells you how to perform the element comparison.

var lista = [{ nombre:"tercero", fecha: "03-01-2019" }, { nombre:"segundo", fecha: "02-01-2019" }, { nombre:"primero", fecha: "01-01-2019" } ];

console.log(lista);

lista.sort((a, b) => {
  // si las fechas tienen formato día-mes-año 
  // entonces hay que manipular un poco para crear el objeto Date correctamente
  var partes = a.fecha.split('-'); 
  var fa = new Date(partes[2], partes[1], partes[0]);
  partes = b.fecha.split('-');
  var fb = new Date(partes[2], partes[1], partes[0]);
  
  return fa - fb;
});

console.log(lista);
    
answered by 03.01.2019 / 22:07
source