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 one?
For example, we want to replace 3452 with 1010, how would we do this?
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 one?
For example, we want to replace 3452 with 1010, how would we do this?
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
}
contains
: var contains = (a, b) => !!~a.indexOf(b)
:P
– Florrie
Nov 12 '15 at 13:13
Array.prototype.includes
instead.
– geon
Sep 5 '18 at 17:15
in
to see if an object has a key (e.g., 'property' in obj
), or you can also loop over an object's values with Object.values(obj).forEach(value => {})
.
– Eli
Mar 27 at 14:40
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; });
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.
– gilly3
Feb 17 '15 at 21:57
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
.
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/…
– InsOp
Oct 20 at 11:15
Use indexOf to find an element.
var i = items.indexOf(3452);
items[i] = 1010;
Easily accomplished with a for
loop.
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 1010;
You can edit any number of the list using indexes
for example :
items[0] = 5;
items[5] = 100;
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'
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);
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]
replace
now..._.replace([1, 2, 3], 2, 3);
– Droogans
Aug 17 '14 at 1:17
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
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);
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;
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;
}
}
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;
};
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.
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]
replaceWhat = 523, replaceWith = 999999
does not yield correct results
– Anthony Chung
Nov 22 at 18:12
replace
method for Arrays? – lifebalance Oct 29 at 6:01