reverse array java
join node js
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"
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
var a = [1,2,3]; //actual array console.log([...a].reverse().join("-")); // working as expected. output: "3-2-1" console.log([...a].reverse().join(""));
Array.prototype.reverse(), The first array element becomes the last, and the last array element becomes The reverse() method reverses an array in place. expected output: "reversed:" Array ["three", "two", "one"] Objects which do not contain a length property reflecting the last in a Array.prototype.join() � Array.prototype.sort()� Written by Maciej Cieślar ️. To use a method on a given array, we type .methodName.They are all defined in the Array.prototype object. Here, however, we won’t be using these; instead, we’ll define our own versions starting from the simple method and build up on top of these until we get them all.
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"
String.prototype.split(), The split() method divides a String into an ordered list of substrings, puts expected output: Array ["The quick brown fox jumps over the lazy dog."] 14 Warning: When the empty string ( "" ) is used as a separator, the string is not split by split() returns an array on which reverse() and join() can be applied. For arrays of numbers, refer to our previous post on sorting array of numbers. Sorting strings can get quite opinionated because of how the sort method works. First of, the ECMAScript standard does not specify a particular sorting algorithm, it all depends on each browser vendor. Second, casing plays a vital role when sorting.
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(""));
- just adding to the first comment... So you reversed your array two times... making it look like the second
a.reverse()didn't work properly, while it reversed already reversed array
a.slice().reverse()is better I think rather than creating a shallow copy.
- @MaheerAli that does the same thing only slice