Is this the best way to replace the first occurrence of something?
my_list[my_list.indexOf(old_item)] = new_item
Note: If the item is not in the array, I don't want anything to happen. (No errors / broken array)
If you're not sure the item is in the list you should do:
var idx = my_list.indexOf(old_item)
if (idx !== -1) { my_list[idx] = new_item }
But else I think it's the best way to do it.
Setting a value at the index -1 won't raise an error, but will still modify the object as would setting a key in a generic js object:
var my_list = [1, 2, 3];
var old_item = 5;
var new_item = 10;
my_list[my_list.indexOf(old_item)] = new_item;
// my_list is [1, 2, 3, '-1': 10]
// my_list.length is still 3
// Object.keys(my_list) is [ '0', '1', '2', '-1' ]
So you probably don't want to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With