Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-destructively reversing an array in Javascript

Tags:

javascript

Say I have a function:

function linesReverser(lines) {
  var localLines = lines.slice(); 
  localLines[1].reverse(); 
  return _.flatten(localLines);
}

And using it like so:

var input = [["Hello"],["Hello", "World"]["Attention", "Please"]];
var output1 = linesReverser(input); //["Hello", "World", "Hello", "Attention", "Please"]
var output2 = linesReverser(input); //["Hello", "Hello", "World", "Attention", "Please"]

Notice how the object reference is being shared. I am new to JS, but I thought copying the values would alleviate this issue (line.slice()), but it doesn't seem to work. Is this because of the nested arrays?

How can I non-destructively/immutably perform a reverse?

like image 300
Dominic Bou-Samra Avatar asked Jan 22 '13 01:01

Dominic Bou-Samra


People also ask

How do I reverse an array without reversing?

To reverse an array without modifying the original, call the slice() method on the array to create a shallow copy and call the reverse() method on the copy, e.g. arr. slice(). reverse() . The reverse method will not modify the original array when used on the copy.


1 Answers

You can duplicate the array using ES6's spread operator, then destructively reverse the duplicate:

const arr1 = [1,2,3];
const arr2 = [...arr1].reverse();
// arr1 => [1,2,3]
// arr2 => [3,2,1]
like image 195
Ryan King Avatar answered Sep 21 '22 10:09

Ryan King