Dhinesh
Dhinesh

Reputation: 67

JavaScript: Array reverse and join is not working as expected for empty tokens in join() method

I am trying to reverse a string and applying join() method on the reversed contents in JavaScript. The join works properly when I use "-" or any other symbol in the join() method. But when I use just ("") or (" ") , it simply joining original array and not the reversed one. Please help me to understand the actual behavior.

Consider the below code.

var a = [1,2,3]; //actual array
console.log(a.reverse().join("-")); // working as expected. output: "3-2-1"
console.log(a.reverse().join(""));  //not working as expected. output:"123"

Thanks, Dhinesh

Upvotes: 2

Views: 2880

Answers (3)

noone
noone

Reputation: 6558

reverse reverse the elements in the original array.

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

var a = [1,2,3]; //actual array
console.log(a.reverse().join("-")); // working as expected. output: "3-2-1"
console.log(a.join(""));  //working as expected. output:"321"

Upvotes: 1

Dave
Dave

Reputation: 2190

It's only a problem of working on the same array and doing two times the reverse operation. Let's try doing this:

var a = [1,2,3]; 
const reversedArr = a.reverse();
console.log(reversedArr.join("-")); 
console.log(reversedArr.join(""));  

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

Reverse mutates original array

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

You can make a shallow copy in this case and than use reverse

var a = [1,2,3]; //actual array
console.log([...a].reverse().join("-")); // working as expected. output: "3-2-1"
console.log([...a].reverse().join("")); 

Upvotes: 4

Related Questions