You can use slice() to make a copy then reverse() it
var newarray = array.slice().reverse();
var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();
console.log('a', array);
console.log('na', newarray);
Answer from Arun P Johny on Stack OverflowReverse an array in JavaScript without mutating the original array - Stack Overflow
How can I reverse an array in JavaScript without using libraries? - Stack Overflow
Making an independent copy of a reversed array in JavaScript - Stack Overflow
How do I reverse an array?
Videos
You can use slice() to make a copy then reverse() it
var newarray = array.slice().reverse();
var array = ['a', 'b', 'c', 'd', 'e'];
var newarray = array.slice().reverse();
console.log('a', array);
console.log('na', newarray);
2023
const newArray = array.toReversed()
Array.prototype.toReversed()
In ES6:
const newArray = [...array].reverse()
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]
You are making a new independent array, but you are not making independent copies of the items that fill your arrays. You need to do something like:
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push({
positionx: input[i].positionx,
positiony: input[i].positiony,
index: input[i].index
});
}
return ret;
}
so that you are generating new objects (with the same properties) as well as the new array.
use this function
function reverseArray(input) {
var newArray = new Array();
for(var i = input.length-1; i >= 0; i--) {
newArray.push(input[i]);
}
return newArray;
}