617

Each item of this array is some number:

var items = Array(523,3452,334,31, ...5346);

How to replace some item with a new one?

For example, we want to replace 3452 with 1010, how would we do this?

1
  • The question is vague. Are you asking how to replace all occurrences of a specific value (3452 in your question), or the first occurrence only, or the element of a specific index (1 in your question)? Do you want the replacing to be done in-place or in a copied array? Commented May 9, 2023 at 0:48

33 Answers 33

753
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
}
Sign up to request clarification or add additional context in comments.

3 Comments

@ValRob you can use findIndex. See this answer: stackoverflow.com/a/53952276/2430274
please what does index !== -1 in the comparison stands for. Thanks
@coderboy Kind of late but the indexOf function returns -1 if the value being searched for was not found in the array.
193

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

a = a.map(item => item == 3452 ? 1010 : item);

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

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

5 Comments

For anyone else reading this. Both map() and forEach() are newer additions to the Javascript spec and aren't present in some older browsers. If you want to use them, you may have to add compatibility code for older browsers: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
Array.indexOf() was introduced at the same time as map() and forEach(). If you are supporting IE8 or earlier, and you aren't using a shim to add in support, better go with mellamokb's answer.
array.map also return index in their second parameter a = a.map(function(item,key) { if (item == 3452) a[key] = 1010; });
@Rickysharma You can do it for the map too, however, it only rewrites the value in the old array, then subsequently creates a copy of the value and returns it. Thus the ternary operator works more efficiently.
The map solution is genius.
134

Answer from @gilly3 is great.

Replace object in an array, keeping the array order unchanged

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);

5 Comments

I would assume that such a loop would be bad if it happens frequently? Would it be better to 'key' the array and make it an object instead or does the JS engine just end up doing the same kind of loop in the end so no performance gain? By keying here I mean to use the user ID as the key in an object. E.g. {1: {}, 2: {}}
Simple method, however, it always loops through the entire array of objects, to only replace a single item.
If you want to maintain the original order and you also can have multiple matches then I don't think so the replacement is possible without iterating all the items. Yes if its a sorted list, then we can apply binary search and then replace the item using the index of the item.
this works good, even can be used when mutating rather than replacing item in list ``` users.map(u => u.id !== editedUser.id ? u : { ...u, someprop:newvalue }); ```
It might not matter to original poster but it is worth noting this solution creates a new array which can be problematic in some situations (namely, Angular reference change detection).
126

My suggested solution would be:

items.splice(start, deleteCount, item1);

Docs

The splice operation will start at index start, remove deleteCount item in the array , and will replace it with the new item item1.

1 Comment

This is misleading as you connote that the first parameter means that 1 item will be removed when in fact the first parameter means that the operation takes place at index 1. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
51

Use indexOf to find an element.

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

1 Comment

what if it does not expected element. if found it will return index of found element but if not it will return -1. and it is going to set that value to -1. please refer jsbin.com/wugatuwora/edit?js,console
37

First method

Best way in just one line to replace or update item of array

array.splice(array.indexOf(valueToReplace), 1, newValue)

Eg:

let items = ['JS', 'PHP', 'RUBY'];

let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')

console.log(replacedItem) //['RUBY']
console.log(items) //['JS', 'PHP', 'PYTHON']

Second method

An other simple way to do the same operation is :

items[items.indexOf(oldValue)] = newValue

1 Comment

Note that both these methods will misbehave if the value to replace is not found in the original array, as Array.indexOf() will return -1 if the element is not found.
31

Easily accomplished with a for loop.

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

1 Comment

Note: this will be the technique with the best performance if you are using nested for-loops, as you can break the loop as soon as you find and replace all the elements needed
26

If using a complex object (or even a simple one) and you can use es6, Array.prototype.findIndex is a good one. For the OP's array, they could do,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

For more complex objects, this really shines. For example,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'

1 Comment

Note that both these methods will misbehave if the value to replace is not found in the original array, as Array.indexOf() will return -1 if the element is not found. In the first case it will add an element with index -1 to your array, which will make your array behave unexpectedly in many ways. In the second case it will just crash for trying to set properties of undefined.
20

You can edit any number of the list using indexes

for example :

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

Comments

19

ES6 way:

const items = Array(523, 3452, 334, 31, ...5346);

We wanna replace 3452 with 1010, solution:

const newItems = items.map(item => item === 3452 ? 1010 : item);

Surely, the question is for many years ago and for now I just prefer to use immutable solution, definitely, it is awesome for ReactJS.

For frequent usage I offer below function:

const itemReplacer = (array, oldItem, newItem) =>
  array.map(item => item === oldItem ? newItem : item);

Comments

16

A functional approach to replacing an element of an array in javascript:

const replace = (array, index, ...items) => [...array.slice(0, index), ...items, ...array.slice(index + 1)];

Comments

9

The immutable way to replace the element in the list using ES6 spread operators and .slice method.

const arr = ['fir', 'next', 'third'], item = 'next'

const nextArr = [
  ...arr.slice(0, arr.indexOf(item)), 
  'second',
  ...arr.slice(arr.indexOf(item) + 1)
]

Verify that works

console.log(arr)     // [ 'fir', 'next', 'third' ]
console.log(nextArr) // ['fir', 'second', 'third']

1 Comment

Very underestimated solution.
7

Replacement can be done in one line:

var items = Array(523, 3452, 334, 31, 5346);

items[items.map((e, i) => [i, e]).filter(e => e[1] == 3452)[0][0]] = 1010

console.log(items);

Or create a function to reuse:

Array.prototype.replace = function(t, v) {
    if (this.indexOf(t)!= -1)
        this[this.map((e, i) => [i, e]).filter(e => e[1] == t)[0][0]] = v;
  };

//Check
var items = Array(523, 3452, 334, 31, 5346);
items.replace(3452, 1010);
console.log(items);

Comments

6

Your question is vague. What exactly are you trying to replace? Are you asking how to replace all occurrences of a specific value (3452 in your question), or the first occurrence only, or the element of a specific index (1 in your question)? Do you want the replacing to be done in-place or in a copied array?


Anyways, I’d like to add some more information on top of the existing answers.

Replacing the element of a specific index…

in-place

with simple assignment.

const array = [523, 3452, 334, 31, 5346];

array[1] = 1010;
console.log(array);

in a copied array

with the Array.prototype.with method.

const array = [523, 3452, 334, 31, 5346];

const copied_and_replaced_array = array.with(1, 1010);
console.log(array, copied_and_replaced_array);

Comments

5

My suggested solution would be:

items = items.with(items.indexOf(oldValue),newValue)

Docs

This line of code using with operation will replace oldValue with newValue in the items array.

1 Comment

ff supported now
4
var items = Array(523,3452,334,31,5346);

If you know the value then use,

items[items.indexOf(334)] = 1010;

If you want to know that value is present or not, then use,

var point = items.indexOf(334);

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

If you know the place (position) then directly use,

items[--position] = 1010;

If you want replace few elements, and you know only starting position only means,

items.splice(2, 1, 1010, 1220);

for more about .splice

Comments

3

The easiest way is to use some libraries like underscorejs and map method.

var items = Array(523,3452,334,31,...5346);

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]

Comments

3

If you want a simple sugar sintax oneliner you can just:

(elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);

Like:

let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
const updatedElement = { id: 1, name: 'updated element one' };

If you don't have id you could stringify the element like:

(elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);

Comments

2
var index = Array.indexOf(Array value);
        if (index > -1) {
          Array.splice(index, 1);
        }

from here you can delete a particular value from array and based on the same index you can insert value in array .

 Array.splice(index, 0, Array value);

Comments

2

Well if anyone is interresting on how to replace an object from its index in an array, here's a solution.

Find the index of the object by its id:

const index = items.map(item => item.id).indexOf(objectId)

Replace the object using Object.assign() method:

Object.assign(items[index], newValue)

1 Comment

This traverses the entire array while looking for the index of a single element. In this case it's best to use Array#findIndex, which short circuits when the first match is found. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
2
 items[items.indexOf(3452)] = 1010

great for simple swaps. try the snippet below

const items = Array(523, 3452, 334, 31, 5346);
console.log(items)

items[items.indexOf(3452)] = 1010
console.log(items)

Comments

1

Here is the basic answer made into a reusable function:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}

1 Comment

let index; while((index = indexOf(findValue)) !== -1) to avoid double indexOf(findValue)
1

Here's a one liner. It assumes the item will be in the array.

var items = [523, 3452, 334, 31, 5346]
var replace = (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr)
console.log(replace(items, 3452, 1010))

Comments

1

const items = Array(1, 2, 3, 4, 5);
console.log(items)

items[items.indexOf(2)] = 1010
console.log(items)

Comments

0

First, rewrite your array like this:

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

Next, access the element in the array through its index number. The formula to determine the index number is: n-1

To replace the first item (n=1) in the array, write:

items[0] = Enter Your New Number;

In your example, the number 3452 is in the second position (n=2). So the formula to determine the index number is 2-1 = 1. So write the following code to replace 3452 with 1010:

items[1] = 1010;

Comments

0

I solved this problem using for loops and iterating through the original array and adding the positions of the matching arreas to another array and then looping through that array and changing it in the original array then return it, I used and arrow function but a regular function would work too.

var replace = (arr, replaceThis, WithThis) => {
    if (!Array.isArray(arr)) throw new RangeError("Error");
    var itemSpots = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == replaceThis) itemSpots.push(i);
    }

    for (var i = 0; i < itemSpots.length; i++) {
        arr[itemSpots[i]] = WithThis;
    }

    return arr;
};

Comments

0
presentPrompt(id,productqty) {
    let alert = this.forgotCtrl.create({
      title: 'Test',
      inputs: [
        {
          name: 'pickqty',
          placeholder: 'pick quantity'
        },
        {
          name: 'state',
          value: 'verified',
          disabled:true,
          placeholder: 'state',

        }
      ],
      buttons: [
        {
          text: 'Ok',
          role: 'cancel',
          handler: data => {

            console.log('dataaaaname',data.pickqty);
            console.log('dataaaapwd',data.state);


          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
                this.cottonLists[i].real_stock = data.pickqty;

            }
          }

          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
              this.cottonLists[i].state = 'verified';   

          }
        }
            //Log object to console again.
            console.log("After update: ", this.cottonLists)
            console.log('Ok clicked');
          }
        },

      ]
    });
    alert.present();
  }

As per your requirement you can change fields and array names.
thats all. Enjoy your coding.

Comments

0

The easiest way is this.

var items = Array(523,3452,334,31, 5346);
var replaceWhat = 3452, replaceWith = 1010;
if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);

console.log(items);
>>> (5) [523, 1010, 334, 31, 5346]

1 Comment

doesn't work for items found at index 0 replaceWhat = 523, replaceWith = 999999 does not yield correct results
0

When your array have many old item to replace new item, you can use this way:

function replaceArray(array, oldItem, newItem) {
    for (let i = 0; i < array.length; i++) {
        const index = array.indexOf(oldItem);
        if (~index) {
            array[index] = newItem;
        }
    }
    return array
}

console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, 5));
console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, "Hi"));

Comments

0
function replaceArray(index, value, arr) { 
        const index_num = arr.indexOf(value)
        const indexed_data = arr[index]
        arr[index] = value;
        arr[index_num] = indexed_data;
        return arr;
}

const arr = [523,3452,334,31, ...5346]
console.log("initial array", arr)
const changed_array = replaceArray(1, 523, arr) // output [3452, 523,334,31, ...5346]
console.log("changed array", changed_array)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.