How to replace item in array?

Solution 1:

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

var items = [523, 3452, 334, 31, 5346];

You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

Sometimes I even like to write a contains function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

if (haystack.includes(needle)) {
    // do your thing
}

Solution 2:

The Array.indexOf() method will replace the first instance. To get every instance use Array.map():

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

Of course, that creates a new array. If you want to do it in place, use Array.forEach():

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

Solution 3:

My suggested solution would be:

items.splice(1, 1, 1010);

The splice operation will remove 1 item, starting at position 1 in the array (i.e. 3452), and will replace it with the new item 1010.

Solution 4:

Answer from @gilly3 is great.

Replace an object in an objects array, keeping the order of elements intact

I prefer the following way to update the new updated record into my array of records when I get data from the server. It keeps the order intact and quite straight forward one liner.

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

var users = [
{id: 1, firstname: 'John', lastname: 'Ken'},
{id: 2, firstname: 'Robin', lastname: 'Hood'},
{id: 3, firstname: 'William', lastname: 'Cook'}
];

var editedUser = {id: 2, firstname: 'Michael', lastname: 'Angelo'};

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

console.log('users -> ', users);

Solution 5:

Use indexOf to find an element.

var i = items.indexOf(3452);
items[i] = 1010;