How to replace an item in an array with JavaScript?

后端 未结 26 2165
执笔经年
执笔经年 2020-11-29 15:33

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 on

相关标签:
26条回答
  • 2020-11-29 16:03

    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; });
    
    0 讨论(0)
  • 2020-11-29 16:03

    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]
    
    0 讨论(0)
  • 2020-11-29 16:06

    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);
    
    0 讨论(0)
  • 2020-11-29 16:07

    You can edit any number of the list using indexes

    for example :

    items[0] = 5;
    items[5] = 100;
    
    0 讨论(0)
  • 2020-11-29 16:07

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

    0 讨论(0)
  • 2020-11-29 16:09

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

    0 讨论(0)
提交回复
热议问题