How to replace item in array?

JavascriptArrays

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

My suggested solution would be:

items.splice(1, 1, 1010);

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

Solution 4 - Javascript

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

Solution 5 - Javascript

Use indexOf to find an element.

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

Solution 6 - Javascript

Easily accomplished with a for loop.

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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'

Solution 9 - Javascript

You can edit any number of the list using indexes

for example :

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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']

Solution 13 - Javascript

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

Solution 14 - Javascript

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]

Solution 15 - Javascript

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

Solution 16 - Javascript

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)

Solution 17 - Javascript

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

Solution 18 - Javascript

 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)

Solution 19 - Javascript

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

Solution 20 - Javascript

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

Solution 21 - Javascript

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

Solution 22 - Javascript

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;

Solution 23 - Javascript

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

Solution 24 - Javascript

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.

Solution 25 - Javascript

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]

Solution 26 - Javascript

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

Solution 27 - Javascript

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

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

Solution 28 - Javascript

This will do the job

Array.prototype.replace = function(a, b) {
    return this.map(item => item == a ? b : item)
}

Usage:

let items = ['hi', 'hi', 'hello', 'hi', 'hello', 'hello', 'hi']
console.log(items.replace('hello', 'hi'))

Output:

['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']

The nice thing is, that EVERY array will have .replace() property.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamesView Question on Stackoverflow
Solution 1 - JavascriptEliView Answer on Stackoverflow
Solution 2 - Javascriptgilly3View Answer on Stackoverflow
Solution 3 - JavascriptShimon AgassiView Answer on Stackoverflow
Solution 4 - Javascriptmuasif80View Answer on Stackoverflow
Solution 5 - JavascriptTesserexView Answer on Stackoverflow
Solution 6 - JavascriptmellamokbView Answer on Stackoverflow
Solution 7 - JavascriptGomsView Answer on Stackoverflow
Solution 8 - JavascriptYatrixView Answer on Stackoverflow
Solution 9 - JavascriptVirtualTrollView Answer on Stackoverflow
Solution 10 - JavascriptAmerllicAView Answer on Stackoverflow
Solution 11 - JavascriptbmaggiView Answer on Stackoverflow
Solution 12 - JavascriptPurkhalo AlexView Answer on Stackoverflow
Solution 13 - JavascriptArteeView Answer on Stackoverflow
Solution 14 - JavascriptmrdedView Answer on Stackoverflow
Solution 15 - JavascriptKarShoView Answer on Stackoverflow
Solution 16 - Javascriptfaye.babacar78View Answer on Stackoverflow
Solution 17 - JavascriptMarco SilvaView Answer on Stackoverflow
Solution 18 - JavascriptWhooNoView Answer on Stackoverflow
Solution 19 - JavascriptJohnP2View Answer on Stackoverflow
Solution 20 - JavascriptGunjan KumarView Answer on Stackoverflow
Solution 21 - JavascriptAlex CoryView Answer on Stackoverflow
Solution 22 - JavascriptAnthony LevatoView Answer on Stackoverflow
Solution 23 - JavascriptJ. SvecView Answer on Stackoverflow
Solution 24 - JavascriptmahendrenView Answer on Stackoverflow
Solution 25 - JavascriptVladimir PrudnikovView Answer on Stackoverflow
Solution 26 - JavascriptAmir KangarlooView Answer on Stackoverflow
Solution 27 - JavascriptRaj ShahView Answer on Stackoverflow
Solution 28 - JavascriptKrzysiekView Answer on Stackoverflow