[Solved] Even Position Element - JS task

  

3
Topic starter

Write a JavaScript function that finds the elements at even positions in an array. The input comes as array of string elements.

Examples:

Input:
['20', '30', '40']

Output:
20 40


Input:
['5', '10']

Output:
5

The output is the return value of your function. Collect all elements in a string, separated by space.

1 Answer
2

Here are my JS solutions:

function evenPosition(arrayString) {
    let result = [];//creating new array named result - to put there the elements from the even positions there
    for (let i in arrayString) {
        if (i % 2 == 0) {
            result.push(arrayString[i]);
        }
    }
    console.log(result.join(" "));
}
 
evenPosition(['20', '30', '40']);
function evenCheck(arr) {
    let arrFiltered = [];
    arrFiltered = arr.filter((x, i)=>i % 2 == 0);//functional programming
    console.log(arrFiltered.join(" "));
}
 
evenCheck(['5', '10', '30', '77']);

The code in 1 row - thanks to the functional programming:

(arrayEven) => arrayEven.filter((x, i)=>i % 2 == 0).join(" ");
Share: