Sort a Object (JS)

0

I have an Object with the following structure:

[
  {
    titulo: '',
    id: '',
    imagen: '',
    fecha: ''
  },
  {
    titulo: '',
    id: '',
    imagen: '',
    fecha: ''
  },
  {
    titulo: '',
    id: '',
    imagen: '',
    fecha: ''
  },
  {
    titulo: '',
    id: '',
    imagen: '',
    fecha: ''
  }
]

I need to sort the object with a function similar to this:

this.articulos.sort( (a, b) => {
  return a.fecha < b.fecha;
});

This works while I'm on the local Angular server, but when I compile it gives me the error error TS2339: Property 'sort' does not exist on type 'Object'.

How can I do this?

    
asked by akko 05.04.2018 в 19:16
source

1 answer

1

Based on MDN Webdocs Mozilla and a similar question resolved in StackOverflow in English . You must bear in mind the following, the sort function is available only for fixes.

// Declaramos arreglo de objetos
var arr = [ 
  {"id": 40},
  {"id": 1},
  {"id": 5},
  {"id": 200}
  ];
  
//Usamos la propiedad sort de los arreglos
arr.sort(function(a,b){
  return a.id - b.id;
});
//M{etodo alternativo con igual resultado
arr.sort((a,b)=>a.id-b.id);

/*Para ver los resultados en tu consola*/

console.log(arr.sort(function(a,b){
  return a.id - b.id;
}));

console.log(arr.sort((a,b)=>a.id-b.id));
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
    
answered by 07.04.2018 в 21:25