The below function created the array modified by comparing array1 to array2 to find either 1) an intitial in array1 that corresponds to a name in array 2 and converts that initial or 2) finds a name in array1 that corresponds to an initial in array2 and converts that name to match the initial.
var array1 = ['fred', 's'];
var array2 = ['sue', 'fred'];
var modified = [];
//create a new modified array that converts initials to names and vice versa
array1.forEach(function(element) {
modified.push(array2.find((el) => el.startsWith(element[0])));
var index = array2.indexOf(array2.find((el) => el.startsWith(element[0])));
if (index > -1) {
array2.splice(index, 1);
}
});
console.log(modified); //['fred', 'sue']
Which is what is expected. Even if there are no initials, the new array will simply match array 1, which is expected.
var array1 = ['fred', 'sue'];
var array2 = ['sue', 'fred'];
console.log(modified); //['fred', 'sue']
if array1 is shorter than array2, it works as expected:
var array1 = ['fred'];
var array2 = ['sue', 'fred'];
console.log(modified); // ['fred']
However, i'm not getting expected results when array 1 is longer than array2:
var array1 = ['fred', 'sue'];
var array2 = ['sue'];
console.log(modified); // ['undefined', 'sue'] // should be ['fred', 'sue']
How can I fix this?