Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to replace the first occurrence of an item in an array

Tags:

javascript

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)

like image 827
lol Avatar asked Oct 29 '22 13:10

lol


1 Answers

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.

like image 89
Guig Avatar answered Nov 11 '22 19:11

Guig