Best way to replace the first occurrence of an element in an array

Is this the best way to replace the first appearance of something?

my_list[my_list.indexOf(old_item)] = new_item 

Note. If the element is not in the array, I do not want something to happen. (No errors / broken arrays)

+5
source share
5 answers

If you are not sure if 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 I think this is the best way to do this.

Setting the value at index -1 will not result in an error, but will still modify the object in the same way as setting the key in a universal 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 this.

+2
source

Not really! There are several ways to do this - one of them you have, the other uses the search method, not indexOf , which is more universal in that it can take regular expression arguments. Note, however, that search not supported in some older JS environments. There are also longer and worse ways, such as using filter or splice , but they will definitely not work better.

The only thing I will do is condition that checks if old_item remains in the list - indexOf returns -1 if something is not in the list, in which case you will replace a nonexistent index.

Basically, I think that everything is in order - it may not be the most beautiful expression, but it is as brief as you can get into JS.

0
source

Arrays are not useful structures for finding values. Instead, you can consider a set:

 my_set.delete(old_item); my_set.add(new_item); 

Note that your code may not be as expected, if old_item does not appear in the array, then indexOf will return -1 . Maybe use something like this:

 var idx = my_list.indexOf(old_item); if (idx >= 0) my_list[idx] = new_item; else my_list.push(new_item); 
0
source

indexOf definitely one of the best ways. But you want to make sure indexOf was successful before using it:

 var index = my_list.indexOf(old_item); if (index !== -1) { my_list[index] = new_item; } 

You can also use the ~ operator if you use short JavaScript:

 var index = my_list.indexOf(old_item); if (~index) { my_list[index] = new_item; } 
0
source

Quick solution using the functions Array.prototype.indexOf and Array.prototype.splice :

 var myList = [1,2,3,4,5], oldItem = 4, newItem = 7; ~(pos = myList.indexOf(oldItem)) && myList.splice(pos, 1, newItem); console.log(myList); 
0
source

Source: https://habr.com/ru/post/1263019/


All Articles