Square at Alternate Indices
Given an array
Sample Input 1
[ 1, 2, 3, 4, 5 ]
Sample Output 1
[ 1, 2, 9, 4, 25 ]
Sample Input 2
[ 2, 4 ]
Sample Output 2
[ 4, 4 ]
const arr1 = [ 1, 2, 3, 4, 5 ];
const arr2 = [ 2, 4 ];
function squareAlternate(arr) {
return arr.map( (item, index) => {
if (index % 2 == 0) {
return item *= item;
} else return item;
})
}
console.log(squareAlternate(arr1));
console.log(squareAlternate(arr2));
Comments
Leave a comment