I have an array in Javascript like so:
var v = new Array("a","b","c","d","e","f"...);
I would like to reverse it but keep the first two elements, so it would turn into:
"a","b",...."f","e","d","c"
How can I do this?
v = [].concat( v.slice(0,2), v.slice(2).reverse());
//v --> ["a", "b", "f", "e", "d", "c"]
v has already been modified. I used [] because initially I wanted to assign the result to a new array, as in var y = [].concat(...)function reverseArrayFromThirdElement(array, copy) {
var arrayCopy = copy ? array.concat() : array;
return [array[0], array[1]].concat(
(arrayCopy.splice(0, 2), arrayCopy.reverse())
);
}
It allows you to choose if you want to keep your array safe from slicing. Pass copy as true if you want your array to be internally copied.
Use destructuring:
const reversedEnd = [...v.slice(0, 2), ...v.slice(2).reverse()];
const reversedBeginning = [...v.slice(0, 2).reverse(), ...v.slice(2)];
const reversedMiddle = [...v.slice(0, 2), ...v.slice(2,4).reverse(), ...v.slice(4)];
It works like Array.Reverse from C#:
const arrayReverse = (arr, index, length) => {
let temp = arr.slice(index, index + length);
temp.reverse();
for (let i = 0, j = index; i < temp.length, j < index + length; i++, j++) {
arr[j] = temp[i];
}
return arr;
};
Example:
let test = ['a', 'b', 'c', 'd', 'e', 'f'];
test = arrayReverse(test, 4, 2);
console.log(test); // returns [ 'a', 'b', 'c', 'd', 'f', 'e' ]
For inplace reversal, this can be done using splice method:
let alp = new Array("a","b","c","d","e","f");
alp.splice(2,4,...alp.slice(2).reverse());
console.log(alp);