Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda