Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating a native JSON array how to limit it to 10 most recent

I am creating a JSON array exactly as follows (bar using mathrandom).

For example purposes:

var numbers = [];
var jsonString = "";

function EveryOneSec() {
  numbers.push(Math.random());
  jsonString = JSON.stringify({'numbers': numbers});
  setTimeout(EveryOneSec, 1000);
}

When I create the JSON string it will obviously just keep getting bigger.

Is there a way that I can only have the 10 most recently added into the array?

like image 921
Sphvn Avatar asked Dec 01 '25 06:12

Sphvn


1 Answers

Add the following code to the top of EveryOneSec

if (numbers.length == 10) {
    numbers.shift();
}

You want to use push and shift to ensure you always have the recent 10.

like image 94
Jason McCreary Avatar answered Dec 02 '25 18:12

Jason McCreary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!