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

Time:08-18

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

CodePudding user response:

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);

CodePudding user response:

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);
    }
}

CodePudding user response:

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