[javascript] How to replace item in array?

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?

This question is related to javascript arrays

The answer is


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


 items[items.indexOf(3452)] = 1010

great for simple swaps. try the snippet below

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

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


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

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

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;

Replacement can be done in one line:

_x000D_
_x000D_
var items = Array(523, 3452, 334, 31, 5346);_x000D_
_x000D_
items[items.map((e, i) => [i, e]).filter(e => e[1] == 3452)[0][0]] = 1010_x000D_
_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Or create a function to reuse:

_x000D_
_x000D_
Array.prototype.replace = function(t, v) {_x000D_
    if (this.indexOf(t)!= -1)_x000D_
        this[this.map((e, i) => [i, e]).filter(e => e[1] == t)[0][0]] = v;_x000D_
  };_x000D_
_x000D_
//Check_x000D_
var items = Array(523, 3452, 334, 31, 5346);_x000D_
items.replace(3452, 1010);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_


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.

Use indexOf to find an element.

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

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

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


To replace the second element in the array

arr = [1, 7, 9]

with the value 8

arr[1] = 8

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]

You can edit any number of the list using indexes

for example :

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

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

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'

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)

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

Easily accomplished with a for loop.

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

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

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


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

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.


Here attached the code which replace all items in array

var temp_count=0;
layers_info_array.forEach(element => {
     if(element!='')element=JSON.parse(element);//change this line if you want other change method, here I changed string to object
     layers_info_array[temp_count]=element;
     temp_count++;
});

Answer from @gilly3 is great.

How to extend this for array of objects

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

_x000D_
_x000D_
var users = [_x000D_
{id: 1, firstname: 'John', lastname: 'Sena'},_x000D_
{id: 2, firstname: 'Serena', lastname: 'Wilham'},_x000D_
{id: 3, firstname: 'William', lastname: 'Cook'}_x000D_
];_x000D_
_x000D_
var editedUser = {id: 2, firstname: 'Big Serena', lastname: 'William'};_x000D_
_x000D_
users = users.map(u => u.id !== editedUser.id ? u : editedUser);_x000D_
_x000D_
console.log('users -> ', users);
_x000D_
_x000D_
_x000D_


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

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

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]

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