Sukumar Dhoni Sukumar Dhoni - 1 month ago 14
AngularJS Question

splice first added object in an array when new element is added in javascript

i am working on splicing the old object ie first added object in an array when new element(object) is added in to it automatically.

this is the sample code i worked on



var sampleArr = [{"id":4,"hostName":"henry"},
{"id":3,"hostName":"jeff"},
{"id":2,"hostName":"mark"},
{"id":1,"hostName":"holder"}];


the above array contains 4 objects when 5 object( {"id":5,"hostName":"punk"}) is added i want to splice first added object ie( {"id":1,"hostName":"holder"}).

here is what i tried in controller



for( var i=0; i<sampleArr.length; i++){
var index = i;
if(sampleArr.length > 4){
sampleArr.splice(index,1,sampleArr[i]);

}
}


but it not working as i expected. please any help me to sought out this!

Answer

You can use the simple pop() to take out the last element and use push to add a new element into the array!

var sampleArr = [{
  "id": 4,
  "hostName": "henry"
}, {
  "id": 3,
  "hostName": "jeff"
}, {
  "id": 2,
  "hostName": "mark"
}, {
  "id": 1,
  "hostName": "holder"
}];



sampleArr.pop()

sampleArr.push({
  "id": 5,
  "hostName": "punk"
})

console.log(sampleArr)