adplus-dvertising

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

Asked 1 month ago
Viewed 20 times

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:""
   }
 ];

asked 1 month ago

Correct Answer

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);
answered 1 month ago

Other Answer

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": ""
    }
]
answered 1 month ago