0

I have an array, a simplified form would be this:

let array = [
  {id: 1, value: 0}, 
  {id: 2, value: 0}, 
  {id: 3, value: 0}
];

Now I want to create an interval, that increments the value on the object with id: 3 every second. What I would do now is target the object with array[2].value. This works as long as the array doesn't change.

The array I use is changing constantly, that means that elements get deleted/add in an asynchronous manner. When that happens the interval is pointing at the wrong element. If I would delete element [1] in the example, the interval would now point at an undefined element ([2]).

I was thinking of using an associative array (id as index), but in Angular ngFor does not work reliably anymore when I do that. Objects are also not working because of the same reason.

How can I create an interval that changes a property of an array element even when the index changes? Or is there a better solution to my problem?

user2324232322
  • 303
  • 2
  • 6
  • 16
  • So you need to target key, instead index? Something like this? https://jsfiddle.net/9jqu6dhv/ – sinisake Dec 16 '17 at 11:50
  • This works. Do you have an explanation why? The code increments the value of the new array .filter created, but somehow the old array changes aswell? :o – user2324232322 Dec 16 '17 at 12:00
  • https://stackoverflow.com/questions/24304383/javascript-return-reference-to-array-item "It returns a new array, but the array's entries are still references to the same objects." – sinisake Dec 16 '17 at 12:11
  • Alright, thanks a lot. This really has to be documented a bit more - no tutorial and not even the mozilla site explains this enough – user2324232322 Dec 16 '17 at 12:15

2 Answers2

1

Use find method:

function updateValue () {
   var item = array.find(item => item.id === 3)
   if (item) item.value++
}

setTimeout(updateValue, 1000)
Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61
eosterberg
  • 1,422
  • 11
  • 11
1

You should hold a reference to the object, instead of using the index each time. For Example:

let array = [
  {id: 1, value: 0}, 
  {id: 2, value: 0}, 
  {id: 3, value: 0}
];

function startIncrementing(elem) {
  setInterval(() => elem.value += 5, 500);
}

// Log the array every second
setInterval(() => console.log(array), 1000);

// Start the increment interval
startIncrementing(array[2]);

// Remove an elemnt after 1 second
setTimeout(() => array.splice(1, 1), 1000);
user184994
  • 17,791
  • 1
  • 46
  • 52