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?
To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.
If you want to replace an object in an array, you can find its index based on one of its property values. To do that, you can use the JavaScript findIndex method. The findIndex function returns the index of the first element matching the condition. It also returns -1 if the condition is not met in the array.
To replace an element in Java ArrayList, set() method of java. util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.
splice() method can be used to add, remove, and replace elements from an array. This method modifies the contents of the original array by removing or replacing existing elements and/or adding new elements in place. Array. splice() returns the removed elements (if any) as an array.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With