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?

4
  • So you need to target key, instead index? Something like this? jsfiddle.net/9jqu6dhv Commented Dec 16, 2017 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 Commented Dec 16, 2017 at 12:00
  • stackoverflow.com/questions/24304383/… "It returns a new array, but the array's entries are still references to the same objects." Commented Dec 16, 2017 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 Commented Dec 16, 2017 at 12:15

2 Answers 2

1

Use find method:

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

setTimeout(updateValue, 1000)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, this works perfectly. Finally not stuck on this issue anymore! :D
Great! Since items in the array are objects, they will still update in the array even if referenced outside.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.