I have names from a database in this format:
lastname mi firstname
And I’d like to change it to
firstname mi lastname
However, I keep getting a numeric value using the stuff Google has told me to do so far:
let s = 'lastname mi firstname'
let sa = s.split(' ')
let correctOrder = sa.unshift(sa.pop()) // 3
let correctOrder = sa.push(sa.shift()); // 3
What is the correct way to move firstname from the last position into the first?
3
Answers
A universal solution regardless of number of words between:
A regex universal solution:
if there’re only 3 words you could use
destructuring
and.join()
:regex
approach:Another approach using
Array#reverse
with
Array#pop
andArray#shift
methods:.split(" ")
the string at every space: " " into an array of stringsNext
.reverse()
the array of stringsFinally,
.join(" ")
the array of strings into a string with a space between the wordsIn the example below is a one-line function — each Array method is chained.