settingsAccountsettings
Menusettings

Q: Even Position Element - JS task

+4 votes

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.

asked in JavaScript category by user golearnweb

3 Answers

+3 votes

My JS function:

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']);

 

answered by user ak47seo
+1 vote

My javascript code:

function evenCheck(arr) {
    let arrFiltered = [];
    arrFiltered = arr.filter((x, i)=>i % 2 == 0);//functional programming
    console.log(arrFiltered.join(" "));
}

evenCheck(['5', '10', '30', '77']);

 

answered by user eiorgert
0 votes

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

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

 

answered by user hues
...