Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse part of an array using javaScript

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?

like image 811
CodeGuy Avatar asked Jul 03 '26 21:07

CodeGuy


2 Answers

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);
  • splice
  • concat
  • reverse
like image 109
PSL Avatar answered Jul 06 '26 09:07

PSL


v = [].concat( v.slice(0,2), v.slice(2).reverse());
//v --> ["a", "b", "f", "e", "d", "c"]
like image 45
pawel Avatar answered Jul 06 '26 09:07

pawel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!