Search code examples
javascriptarrayssortingnumberslogic

Print alternatively one element from the last and one from the first (JavaScript)


Print alternatively one element from the last and one from the first (JavaScript)

input 1, 3, 6, 3, 2, 8

output: 8, 1, 2, 3, 3, 6


Solution

  • You can use the below approach

    var array = [];
    var size = prompt('Enter Array Size'); //Maximum Array size
    
    for(var i=0; i<size; i++) {
        
        //Taking Input from user
        array[i] = prompt('Enter Element ' + (i+1));
    }
    
    //Print the array in the console.
    console.log("Array Input: "+array.join(','));
    
    let output = [];
        let l = array.length - 1;
        for (let i = 0; i <= l; i++, l--) {
            if (i>=array.length/2) {
                console.log(array[i]);
                break;
            }
            output.push(array[l]);
            output.push(array[i]);
        }
    
    console.log("Resultant Array: "+output.join(','));