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

108
Vistas
If the name value is empty, I need to change it to the end of the array in Javascript

I have an array. If the name value is empty, I need to change it to the end of the array, how can I do that in Javascript?

ex:

 const data : [
   {
     id:0,
     name:"gorkem"
   }
   {
     id:1,
     name:""
   }
   {
     id:2,
     name:"ahmet"
   }
 ];

Replace

const data : [
   {
     id:0,
     name:"gorkem"
   }
   {
     id:2,
     name:"ahmet"
   }
   {
     id:1,
     name:""
   }
 ];
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Use two calls to filter, one to get the items with non-empty name, the other with the empty names. Then concatenate these two arrays.

let non_empty = data.filter(el => el.name);
let empty = data.filter(el => !el.name);
let result = non_empty.concat(empty);
about 4 years ago · Santiago Trujillo Denunciar

0

First of all you need to have a valid array:

const data = [{
    id:0,
    name:"gorkem"
}, {
    id:1,
    name:""
}, {
    id:2,
    name:"ahmet"
}];

So, starting with that you can use a loop to remove empty name element and add to the end:

for (let i = 0; i < data.length; i++) {
    if (data[i].name === '') {
        let val = data[i];
        data.splice(i, 1);
        data.push(val);
    }
}
about 4 years ago · Santiago Trujillo Denunciar

0

You could just sort the array based on the "truthiness" of the "name".

const data = [{
    id:0,
    name:"gorkem"
}, {
    id:1,
    name:""
}, {
    id:2,
    name:"ahmet"
}];

console.log(data.sort((a,b)=>!a.name - !b.name));

Above, we are basically abusing the fact that an empty string is a falsy value which is equivalent to 0, while a non empty string is truthy, which is equivalent to 1. Each are negated with a "!" to get the reversed sort order you are after and to actually treat them as booleans.

result :

[
    {
        "id": 0,
        "name": "gorkem"
    },
    {
        "id": 2,
        "name": "ahmet"
    },
    {
        "id": 1,
        "name": ""
    }
]
about 4 years ago · Santiago Trujillo 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