Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
One line Array iterator javascript

I am coming from Python and I am looking for a single line iterator function for any array, where I can also check a condition and return a simple change to the items.

Expected result should match the method:

function arrayEvenItemIncrement(myArray){
    for (let i = 0; i < myArray.length; i++){
        if (myArray[i]%2==0){
            myArray[i]++;
        }
    }
    return myArray;
}

I tried using for (i of myArray){ } but this still doesn't serve my purpose.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think the clearest way to do what you want here would be to map to a new array instead of mutating the old one:

const arrayEvenItemIncrement = myArray =>
  myArray.map((val, i) => i % 2 === 1 ? val : val + 1);

If you have to mutate the existing array, it gets significantly uglier.

const arrayEvenItemIncrement = myArray => (
  myArray.forEach((val, i) => { if (i % 2 === 0) myArray[i]++; }), myArray);

or

const arrayEvenItemIncrement = myArray => {
  myArray.forEach((val, i) => { if (i % 2 === 0) myArray[i]++; }); return myArray };

But I wouldn't recommend that - put it on multiple lines instead.

You can technically squeeze any JS code into a single line, but past simple manipulations, it usually isn't a good idea because it sacrifices readability, which is far more important than reducing LoC. Professional, maintainable code is not a golfing competition.

about 4 years ago · Juan Pablo Isaza Report

0

Thank you for the answers. I have settled for this:

myArray.forEach(el=>el%2===0?newArray.push(el):null);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!