Move a particular value object in array to end

I'm trying to find a way to move an object to the end of the array

I have this array of objects:

[
  {"id":"4","name":"Boaz"},
  {"id":"2","name":"Shareen"},
  {"id":"3","name":"Simon"},
  {"id":"1","name":"Miriam"}
]

I want to move the whole set {"id":"3","name":"Simon"} to the end of it all. I have solution for this here. But my problem is every time that particular object is not coming in second position is there a way to check the object of id=3 and shift that to end using underscoreJS

Answers 1

  • Can you try this with the getting index of the respective object and then check the position:

    var array  = [{ "id": "4", "name": "Boaz" }, { "id": "2", "name": "Shareen" }, { "id": "3", "name": "Simon" }, { "id": "1", "name": "Miriam" }];
    
    var index =  array.findIndex(x => x.id == 3);
    
    if(index === 2) {
     var person =  array.splice(index, 1);
     array  = array.concat(person);
    }
    
    console.log(array)


Related Articles