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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With