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 can I modify every other element in an array using JS?

So the data is like this:

let array = ["Yes", "Yes", "Yes", "Yes"];

Expected Result:

array = ["Yes", "", "Yes", ""];

I’ve seen some answers on Stackoverflow, but I haven’t found one that shows how to modify every other element. Most show how to filter, like this one:

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

let x = arrar.filter((element, index) => {
  return index % 2 === 0;
})

Appreciate your help!

>Solution :

As Emiel pointed out in the comments, you don’t want to use .filter() here as that would reduce your original array. Instead use .map():

let array = ["Yes", "Yes", "Yes", "Yes"];

let x = array.map((element, index) => {
  return (index % 2 === 0) ? element : '';
})

console.log(x)
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