How to sort an array of Javascript objects through an object value

Asked

Viewed 268 times

2

I’m wondering how I can organize an array of objects in Javascript through the creation date of the item that comes as a value in the object, follow an example:

[
  {
    ...valores,
    requestedCase: {
       ...valores,
       creationDate: "2020-02-04T17:18:02"
    }
  },
  {
    ...valores,
    requestedCase: {
       ...valores,
       creationDate: "2020-01-31T13:49:22"
    }
  }
]

When I receive this data from the API, I would like to create a new array with the items sorted decreasing through the creationDate.

I did some research and I couldn’t find anything that would solve my problem, can someone please help me!

3 answers

4


Use the method .sort() converting the value of creationDate on date:

const api = [
  {
    requestedCase: {
       creationDate: "2020-01-31T13:49:22"
    }
  },
  {
    requestedCase: {
       creationDate: "2020-01-31T13:48:02"
    }
  },
  {
    requestedCase: {
       creationDate: "2020-02-04T17:18:02"
    }
  }
];

const decrescente = api.sort(function(a,b){
   return new Date(b.requestedCase.creationDate) - new Date(a.requestedCase.creationDate);
});

console.log(decrescente);

  • 1

    Thanks Sam!!! It worked here!

3

Below is a demostrative code.

The important thing is to create a sort function, in your case:

function dataDecrescente(a, b) {
  return a.creationDate < b.creationDate ? 1 : a.creationDate > b.creationDate ? -1 : 0
}

This will be the callback called in function .sort array. It might be interesting to put a new Date() with the parameters.

After that just call the sorting method of your array by passing the callback as follows:

array.sort(dataDecrescente);

// função para ordenação
function dataDecrescente(a, b) {
  return a.data < b.data ? 1 : a.data > b.data ? -1 : 0
}
// criar estrutura que será ordenada
let teste = [];
let i = 1;
const interval = setInterval(() => {
  teste.push({
    'id': i++,
    'data': new Date().toISOString()
  })
}, 200);
//tempo para que a estrutura seja populada
setTimeout(() => {
  clearInterval(interval); // para a população da estrutura
  console.log(teste.sort(dataDecrescente)); // resposta com a ordenação da estrutura de forma decrescente
}, 5000);

2

Try something like this, he orders by the object Date() , the slice() is to disaggregate from the original object:

var valores = [1, 2, 3, 4, 5];

var data = [
  {
    ...valores,
    requestedCase: {
       ...valores,
       creationDate: "2020-02-04T17:18:02"
    }
  },
  {
    ...valores,
    requestedCase: {
       ...valores,
       creationDate: "2020-01-31T13:49:22"
    }
  }
];


var result = data.slice().sort((a, b) => new Date(a.requestedCase.creationDate) > new Date(b.requestedCase.creationDate) ? 1 : -1);

console.log(result);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.