I recently encountered an issue with reversing and joining an array in JavaScript. I had an array named arr with values [a, a, b, c, d]. My intention was to reverse the array and then join it together to create a string. Here is the code snippet I used:
arr.reverse().join('');
The expected output should have been 'dcbaa' but instead, I got 'aabcd'. This discrepancy left me questioning if I misunderstood the functionality of the code. Was the reverse function reversing the array only for it to be lost when passed to the join function? I thought about reversing a string using:
str.split('').reverse().join('');
Since I already had the array, I excluded the initial split step. Any insights on this matter would be highly appreciated.
EDIT FOR CONTEXT: I was working on a function to identify palindromes. The function takes a string input and searches for the longest palindrome within that string. Below is a snippet of the code I used:
longestPalindrome=function(s){
var strlen = 0;
var stringArr = s.toLowerCase().split('');
var chunk = '';
if(s.length === 0){
return strlen;
}
//for loop to go through each letter
for(var i = 0; i < s.length; i++){
//for loop to grab increasing chunks of array (a, ab, abc, abcd, etc.)
for(var j = 0; j < s.length - i; j++){
//Grab piece of string and convert to array
chunk = stringArr.slice(i, (s.length - j));
//View new array
console.log(chunk);
//Reverse chunk for later comparison
var chunkReverse = chunk.reverse();
//Check what the reversed array looks like
console.log(chunkReverse);
//Create string from chunk
chunk = chunk.join('');
//view string from former chunk array
console.log(chunk);
//Create string from reversed array
chunkReverse = chunkReverse.join('');
//View reversed string from chunk array
console.log(chunkReverse);
}
}
return strlen;
}
The sample outputs from the code above were as follows (using dummy data from the original post):
[a,a,b,c,d]
[d,c,b,a,a]
aabcd
aabcd
I hope this helps clarify the situation.