just_trying_to_learn just_trying_to_learn - 1 month ago 8
Javascript Question

Finding Multiple Instances of String in Array & Reordering

My problem is as follows: I am trying to take data as formatted in the 'names' variable in the snippet below, convert the string to array, then reorganize the array so the text is in the correct order. I am able to get the pieces I have put together to properly sort the first or last instance of a first & last name, but am seeking guidance on how to go about processing multiple names. The snippet below will return the last instance of the first & last name in the correct order. At this point, I am only looking to have the data returned as a properly sorted array, e.g.

if the input string is

names = "Bond, James & Banner, Bruce";


once processed should return:
['James', 'Bond,', '&', 'Bruce', 'Banner,']


As always I appreciate all the help I can get, thanks 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 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);




Answer

You were close but this solution should work for you. Basically you need to update in the loop and increment the index i to account for the switch. Otherwise you will end up revisiting the first last name you switch.

Array.prototype.move = function(from,to){
  this.splice(to,0,this.splice(from,1)[0]);
  return this;
};

var names ="Bond, James & Banner, Bruce & Guy, Other";

var namesArr = names.split(' ');
var idx;

// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
  if(namesArr[i].indexOf(',') != -1) {
    namesArr.move(i, i+1);
    i++; 
  }
}

console.log(namesArr);

Comments