Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
How to shift an object on top position in existing array in javascript, if the object have some specific key

I have two array friend[] and messages[] and I have already inserted message array values in the friend array according to their friend id. Now, the main array is the friend array which includes some messages like some friends have messages and some have not. But I want to sort friend array based on the message created_Date, and those friend who have not any messages inside their object they remain same. Here is my code:

data.sort((a, b) => (a.lastMessage ? new Date(a.lastMessage.createdAt).getTime() < new Date(b.lastMessage.createdAt).getTime() : '') ? 1 : -1)

Here is my output which is not sorted according to the last message date:

{
"data": [
    {
        "block": false,
        "user": {
            "_id": "60ed4a8c1e0812bb34674983",
            "profilePic": "",
            "firstName": "sachin",
            "lastName": ""
        },
        "friend": {
            "_id": "612d11535c77de82c8a68b0d",
            "profilePic": "fsjalk;gja./.coj",
            "firstName": "Sachin4",
            "lastName": "Kumar"
        }
    },
    {
        "block": true,
        "user": {
            "_id": "60ed4a8c1e0812bb34674983",
            "profilePic": "",
            "firstName": "sachin",
            "lastName": ""
        },
        "friend": {
            "_id": "60ed4838ea237d0b40a16491",
            "profilePic": "",
            "firstName": "sachin",
            "lastName": ""
        }
    },
    {
        "block": false,
        "user": {
            "_id": "60ed4a8c1e0812bb34674983",
            "profilePic": "",
            "firstName": "sachin",
            "lastName": ""
        },
        "friend": {
            "_id": "612d108d14521e598838690e",
            "profilePic": "",
            "firstName": "Sachin3",
            "lastName": "Kumar"
        },
        "lastMessage": {
            "message": "This is my sixth chat.",
            "createdAt": "2021-09-06T13:47:50.082Z"
        }
    }
]

}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Concat elements without lastMessage to sorted elements with lastMessage using Array.filter.

Here's a minimal reproducable example

const data = getData();
const sorted = data.filter(d => d.lastMessage)
  .sort((a, b) =>
    new Date(a.lastMessage.createdAt) -
    new Date(b.lastMessage.createdAt))
  .concat(data.filter(d => !d.lastMessage));

document.querySelector(`pre`).textContent =
  JSON.stringify(sorted, null, 2);

function getData() {
  return [
    {
      "user": {
        "_id": "60ed4a8c1e0812bb34674983",
      }
    },
    {
      "user": {
        "_id": "60ed4a8c1e0812bb34674983",
      },
      "lastMessage": {
        "createdAt": "2021-09-06T13:47:50.082Z"
      }
    },
    {
      "user": {
        "_id": "60ed4a8c1e0812bb34674983",
      },
    },
    {
      "user": {
        "_id": "60ed4a9c140e19bb34674983",
      },
      "lastMessage": {
        "createdAt": "2020-04-02T23:11:12.154Z"
      }
    },
  ];
}
<pre></pre>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda