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
Easily accomplished with a for
loop.
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 1010;
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
}
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'
Use indexOf
to find an element.
var i = items.indexOf(3452);
items[i] = 1010;
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
.
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