I am facing an issue with organizing data stored in the 'names' variable within the code snippet. The task at hand involves converting a string into an array, rearranging the elements within the array to ensure the text is in the correct order. While I have managed to successfully sort the first or last instance of a first & last name individually, I am now looking for guidance on how to handle multiple names efficiently. The current implementation only sorts the last occurrence of the first & last name correctly.
If we consider the input string:
names = "Bond, James & Banner, Bruce";
After processing, the expected output should be:
['James', 'Bond,', '&', 'Bruce', 'Banner,']
Your assistance and insights are highly appreciated. Thank you in advance!
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas along with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
idx = i;
}
}
namesArr.move(idx, idx+1);
console.log(namesArr);