settingsAccountsettings
Menusettings

Q: Process Odd Positions in Array (JavaScript Task)

+3 votes

You are given an array of numbers. Write a JavaScript code/function that prints the elements at odd positions from the array, doubled and in reverse order. The input comes as array of number elements.

Examples:

Input:
[10, 15, 20, 25]

Output:
50 30


Input:
[3, 0, 10, 4, 7, 3]

Output:
6 8 0

The output is printed on the console on a single line, separated by space.

asked in JavaScript category by user golearnweb

2 Answers

+2 votes

My Js code:

function firstLastKElements(arrNum) {
    let odd = (arrNum.filter((num, i)=>i % 2 == 1));//filter the array to get the odd positions i
    //console.log(odd);//just checking
    let double = odd.map(x=>x * 2);
    //console.log(double);//just checking
    let reverse = (double.reverse()).join(" ");
    console.log(reverse);
}

firstLastKElements([10, 15, 20, 25]);

 

answered by user samfred5830
0 votes

My program:

function solve(arr) {
    let result = arr
        .filter((num, i)=>i % 2 == 1)
        .map(x=>x * 2)
        .reverse()
        .join(" ");
    console.log(result);
    //or in one row:
    //let result = arr.filter((num, i)=>i % 2 == 1).map(x=>x * 2).reverse().join(" ");
}

solve([3, 0, 10, 4, 7, 3]);

 

answered by user sam
...