¿Cómo reemplazar un elemento en una matriz con Javascript?


Cada elemento de esta matriz es un número.

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

¿Cómo remplazo un número con arreglo por uno nuevo?

Por ejemplo, queremos reemplazar 3452 con 1010, ¿cómo lo haríamos?

Author: Flip, 0000-00-00

11 answers

var index = items.indexOf(3452);

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

También se recomienda que no utilice el método constructor para inicializar sus matrices. En su lugar, use la sintaxis literal:

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

También puede usar el operador ~ si está interesado en JavaScript conciso y desea acortar la comparación -1:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

A veces incluso me gusta escribir una función contains para abstraer esta comprobación y facilitar la comprensión de lo que está pasando. Lo que es impresionante es que esto funciona en matrices y cadenas tanto:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

Empezando por ES6/ES2015 para cadenas, y propuesto para ES2016 para matrices, puede determinar más fácilmente si una fuente contiene otro valor:

if (haystack.includes(needle)) {
    // do your thing
}
 294
Author: Eli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-12 13:20:33

El método Array.indexOf() reemplazará la primera instancia. Para obtener cada instancia use Array.map():

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

Por supuesto, eso crea una nueva matriz. Si desea hacerlo en su lugar, utilice Array.forEach():

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });
 54
Author: gilly3,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-06 19:03:03

Utilice indexOf para encontrar un elemento.

var i = items.indexOf(3452);
items[i] = 1010;
 19
Author: Tesserex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-06 18:55:45

Se logra fácilmente con un bucle for.

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;
 16
Author: mellamokb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-06 18:55:18

Puede editar cualquier número de la lista utilizando índices

Por ejemplo:

items[0] = 5;
items[5] = 100;
 7
Author: VirtualTroll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-14 04:54:58

La forma más fácil es usar algunas bibliotecas como underscorejs y map method.

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

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]
 2
Author: mrded,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-11 21:35:33
var items = Array(523,3452,334,31,5346);

Si conoces el valor entonces usa,

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

Si quieres saber que el valor está presente o no, entonces usa,

var point = items.indexOf(334);

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

Si conoces el lugar (posición) entonces usa directamente,

items[--position] = 1010;

Si desea reemplazar algunos elementos, y solo sabe que la posición inicial solo significa,

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

Para más información sobre .splice

 2
Author: KarSho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-26 03:10:29

Primero, reescribe tu matriz de la siguiente manera:

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

A continuación, acceda al elemento en la matriz a través de su número de índice. La fórmula para determinar el número índice es: n-1

Para reemplazar el primer elemento (n=1) en la matriz, escriba:

items[0] = Enter Your New Number;

En su ejemplo, el número 3452 está en la segunda posición (n=2). Así que la fórmula para determinar el número de índice es 2-1 = 1. Así que escribe el siguiente código para reemplazar 3452 por 1010:

items[1] = 1010;
 0
Author: Anthony Levato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 01:42:01

Usando jQuery, podría ser fácil:

var items = Array(523,3452,334,31,5346);
var val = 3452; // we want to replace this
var index = $.inArray(val, items); // get index of specific value

items[index] = 1010; // execute!
alert(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 0
Author: Ukasyah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-23 00:47:20

Aquí está la respuesta básica convertida en una función reutilizable:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}
 0
Author: JohnP2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-13 21:43:00

Mi solución sugerida es:

Items.empalme (1,1,1010)

Explicación: La operación de empalme eliminará 1 elemento, comenzando en la posición 1 en la matriz (es decir, 3452), y lo reemplazará con el nuevo elemento (1010).

 0
Author: Shimon Agassi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-29 07:38:29