Anupam Arya
Anupam Arya

Reputation: 199

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.

Upvotes: 2

Views: 1412

Answers (2)

Anupam Arya
Anupam Arya

Reputation: 199

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

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370969

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.

Upvotes: 2

Related Questions