Sukumar Dhoni Sukumar Dhoni - 1 year ago 81
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"},

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


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

Answer Source

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"


  "id": 5,
  "hostName": "punk"


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download