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.
CodePudding user response:
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.
CodePudding user response:
The Array method .reduce(prv, cur, idx, arr) is perfect for shrinking an array of values into a single value. The main function of the example below, countEven(arr), is at it's core is a simple callback which is just a basic ternary (ie if/else as an expression). The counting is streamlined as well -- it relies on the first argument of .reduce(): prv (in the example it is cnt) to increment by 1 on every iteration in that there's a number with even parity. Normally, a counter would require operating in nested functions, implementing a closure, etc.
Details are commented in example
/** FOR DEMO ONLY - NOT REQUIRED
** log(anyValue) formats
** console.log for readability.
*/
const log = data => console.log(JSON.stringify(data));
/** FOR DEMO ONLY - NOT REQUIRED
** genArr(arrLength, 100)
** returns an array of random
** numbers. Array length
** is required and max value
** is optional (defaults to 100)
*/
const genArr = (len, max = 100) => new Array(len).fill(0).map(o => Math.floor(Math.random() * max));
/** countEven(arr) returns a
** count of all even parity
** numbers of a given array
** of numbers.
*/
const countEven = arr => arr.reduce((cnt, cur) => cur === 0 || cur % 2 === 1 ? cnt : cnt 1, 0);
/** In the callback, cnt is
** incremented when cur is even.
*/
let test = genArr(30);
log(test);
log(countEven(test));
.as-console-row::after {
width: min-content;
font-size: 0;
}
.as-console-row-code {
width: max-content;
word-break: break-word
}
