简体   繁体   中英

How to remove the number of last items in the array using javascript?

Consider i'm having dynamic array where my items keeps on increment each second. So i want to remove the last 30 items in the array when array reaches to 60 and keeps the rest in. That is i want to maintain only 30 items in array and remove the older items.

array=[1,2,3,4...........60] //Remove last 30 and show new 30 items
array=[21,22,23...30]

Please suggest me how to achieve this. My Code

If what you want is to drop elements after the 30th

array.length=30;

If you want to drop all but the last 30

array.splice(0, array.length - 30);

here's a demo of both (using 10 instead of 30 for readability of output)

 const array = Array.from({length:60}, (_, i) => i); array.length = 10; console.log(JSON.stringify(array)); const array2 = Array.from({length:60}, (_, i) => i); array2.splice(0, array2.length - 10); console.log(JSON.stringify(array2)); 

var arr = [1,2,3,4....,60];

function arr_modify(arr,removeLength){
  if(arr.length == 60){
    arr.splice(0,removeLength)
  }
 return arr;
}

var modified_array = arr_modify(arr,30);
console.log(modified_array);
console.log(arr);

If you want to keep last N of items use this code:

 let numberOfItemsToRemain = 5; let array = [1,2,3,4,5,6,7,8,9,10]; let size = array.length; array = array.splice(size-numberOfItemsToRemain, size); console.log(array); 

If you want to keep first N of items, use this code:

 let numberOfItemsToRemain = 5; let array = [1,2,3,4,5,6,7,8,9,10]; array = array.splice(0, numberOfItemsToRemain); console.log(array); 
*Edit numberOfItemsToRemain to 30 in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM