How to replace an item in an array with Javascript?

How to replace an item in an array with Javascript?

Each item of this array is some number.
var items = Array(523,3452,334,31, …5346);

How do I replace some number in with array with a new one?
For example, we want to replace 3452 with 1010, how would we do this?

Solutions/Answers:

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:

Related:  Can a PDF file's print dialog be opened with Javascript?
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:

Use indexOf to find an element.

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

Solution 4:

Easily accomplished with a for loop.

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;

Solution 5:

You can edit any number of the list using indexes

for example :

items[0] = 5;
items[5] = 100;

Solution 6:

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.