Hristijan Ilieski Hristijan Ilieski - 10 months ago 98
Javascript Question

Remove element from array on timeout Node.js

I have an array that is very dynamic, there are new elements all the time, and other elements are removed.. The problem is that sometimes, under some circumstances, it's possible some of the elements to stay in the array forever and that is NOT what I want. Every element should be removed from the array within 15 seconds, if not, the array should remove that element automatically.

For example, in the code below, we have an array with three elements:

var array = ['e1', 'e2', 'e3'];

After 5 seconds I am adding 2 more elements in the array:

array[3] = 'e4';
array[4] = 'e5';

Now, let's say that the first 3 elements are inserted in the array in 12:00:00pm, and the second 2 elements in 12:00:05pm. I want the first 3 elements to be removed in 12:00:15pm, and the second 2 elements in 12:00:20pm......Etc....

Are there any ideas on how to solve this problem?

Answer Source

Generally, when you are adding items to an array, you don't want to assume the position they will exist at. Instead of array[3] = 'e4', do array.push('e4'). This will make your life easier, and less bug-prone.

Because you need to associate times with each item, it might be wise to use objects for this in place of strings.

// create the array and push some objects into it
var array = []
array.push({createdAt:, value: 'asdf'})
array.push({createdAt:, value: 'asdf'})

Then, in an interval, you can check the createdAt values of each of the objects and decide if you want to kick them out of the array.

var maxLifespan = 5000
// check once per second
setInterval(function checkItems(){
        if( - maxLifespan > item.createdAt){
            array.shift() // remove first item
}, 1000)

Using array.shift() assumes that you will always push new items onto the end of the array, so they will always be sorted chronologically.

If you need the array to be not chronologically sorted, then you'd need to use a method for removing elements at a specific index in an array (hint: NOT delete). Use array.splice to achieve this.