Show array in reverse order

Asked

Viewed 184 times

1

I thought of this code to show the reverse order. It worked, but I was wondering if there is another possible way.

function inversa(...ray){
    console.log(`Os elementos do array são: ${ray.join(', ')}.`)
    if(ray.length == 6){
        let inverso = ray.sort((num, num2) => num2 - num)
        return `A ordem inversa da array é: ${inverso.join(', ')}.`
    }else
        return 'A quantidade de números está errada.'
}
console.log(inversa(1,2,3,4,5,6))

1 answer

5


The Reverse() method inverts the items of an array. The first element of the array becomes the last and the last becomes the first.

    
var numeros = [1,2,3,4,5,6];
numeros.reverse();

console.log(numeros);

One more option

function reverte(num) {
    var ret = new Array;
    //pega os valores do ultimo para o primeiro
    for(var i = num.length-1; i >= 0; i--) {
        //O método push() adiciona ao final do array
        ret.push(num[i]);
    }
    return ret;
}

var a = [1,2,3,4,5,6]
var b = reverte(a);

console.log(b);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.