Reversing an Array in JavaScript.
How can I reverse an array in JavaScript without using libraries? - Stack Overflow
How do I reverse an array?
How do i reverse an array in javaScript without .reverse()
Videos
Javascript has a reverse() method that you can call in an array
var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);
Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.
Array.prototype.reverse()is all you need to do this work. See compatibility table.
var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]
I'm trying to print this array in reverse order but I don't really know much about JavaScript and I thought I found a solution but it only works with numbers and I don't really know what to do. Any help I'm thankful for
Heres my code
var array = ["Item1, Item2, Item3"];
for(var a = array.length-1; a >= 0; a--) {
document.write(array[a]);
}
I've found out that your code almost works. You just need to modify the condition a bit to
i < (list.length / 2) //not `<=`
function rev(list) {
for (let i = 0, j = (list.length - 1); i < (list.length / 2); i++, j--) {
[list[i], list[j]] = [list[j], list[i]];
}
return (list);
};
console.log(rev([1, 2, 3, 4, 5]));
console.log(rev(["School", 89, { id: 12 }, "String"]));
let array = [1, 2, 3, 4, 5]
let reverse = [];
for (var i = array.length - 1; i >= 0; i--){
reverse.push(array[i]);
}