views:

58

answers:

3

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?

+3  A: 

There will be a few ways to handle this, but here is one (Comments added):

Note I took the OP's question very literally. This lets the numbers array continue to grow, but limits the JSON version to only 10 items.

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

function EveryOneSec() {
  numbers.push(Math.random());
  // Get total number, minus 10 to get starting index
  var l = numbers.length - 10;

  // If l < 10 there are less than ten items, pass 0 to slice.
  // otherwise pass the starting index to get the last 10 numbers
  jsonString = JSON.stringify({'numbers': numbers.slice(l < 0 ? 0 : l)});
  setTimeout(EveryOneSec, 1000);
}
Doug Neiner
To me, this looks cleaner: `numbers.length > 10 ? numbers.slice(-10) : numbers`.
Casey Hope
@Casey, that looks a lot cleaner... great suggestion!
Doug Neiner
+5  A: 

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.

Jason McCreary
+1 Great answer Jason!
Doug Neiner
@Doug. True, you caught me in the middle of an edit ;)
Jason McCreary
@Jason haha, I am just that fast ;) No, I wanted to upvote, but I had to wait until it was fixed!
Doug Neiner
Thankyou for the fast reply works well :)
Thqr
@Ozaki. No problem. But the quickness goes to **Doug**
Jason McCreary
A: 

You could dispense with the problem of checking whether the size is ten or not by using

var number = Array(10);

Two downsides you would have to keep a running total of the index i++ instead of using numbers.push and the JSON string would contain the blank spaces. However, if I remember correctly numbers[numbers.length] = is supposed to be faster then numbers.push(). So tracking your index might be faster.

qw3n