Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace one element of array inside loop

There is an array arr = [1, 2, "a", 4, 5];. Using loop (for…of) every element of array must be pushed inside another empty array result = [];.

But, inside arr there is an element that needed to be replaced inside loop. Here, we need to replace string "a" with number 3 and than push it inside array result.

In the end we need to get an array result = [1, 2, 3, 4, 5];. As you can see string "a" was replaced and instead number 3 was pushed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

!Important initial array arr shouldn’t be mutated and loop is a required condition.

Example:

const arr = [1, 2, "a", 4, 5];
const result = [];

for(let elem of arr) {
  if(typeof elem === "string") {
    // changing elem to number 3 and pushing it into result array instead of "a"
  }
// ...
}

Tried use several different array methods, but it didn’t help.

>Solution :

You can replace the string "a" with the number 3 and push every element into a new array using the for…of loop as follows:

const arr = [1, 2, "a", 4, 5];
const result = [];

for (let elem of arr) {
  if (typeof elem === "string" && elem === "a") {
    // replace "a" with number 3 and push it into the result array
    result.push(3);
  } else {
    // push the current element into the result array
    result.push(elem);
  }
}

console.log(result); // [1, 2, 3, 4, 5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading