Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace item in array?

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?

like image 918
James Avatar asked May 06 '11 18:05

James


People also ask

How do you replace an element in an array?

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.

How do you replace values in an array of objects?

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.

How do you replace something in an array Java?

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.

How can you remove an element from an array and replace it with a new one?

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.


1 Answers

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 } 
like image 158
Eli Avatar answered Oct 08 '22 01:10

Eli