2

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?

0

6 Answers 6

12

Try this way:

var v = new Array("a","b","c","d","e","f");
var newArr = v.splice(0,2).concat(v.reverse()); // get the first 2 out of the array
console.log(newArr);
Sign up to request clarification or add additional context in comments.

Comments

6
v = [].concat( v.slice(0,2), v.slice(2).reverse());
//v --> ["a", "b", "f", "e", "d", "c"]

4 Comments

why the array literal, wouldn't just v.slice(0,2).concat(v.slice(2).reverse()) work?
@dandavis yeah, sorry, I've tried it in a context where v has already been modified. I used [] because initially I wanted to assign the result to a new array, as in var y = [].concat(...)
gotcha, looks good. note sure if slice or splice is faster, but ti's good to have options for when splice is not present.
@PSL yeah, my solution is slower, by far. jsperf.com/slice-vs-splice-array
2
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.

Comments

1

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)];

Comments

0

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' ]

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.