Converting an initial in one array to match a full name in another works, but not when arrays are different lengths

问题: 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...

问题:

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?


回答1:

You're pushing the result of .find() onto modified even if it doesn't find anything. You should default to the string you're searching for.

And instead of calling .find() twice, use findIndex() to get the index once, and use that when pushing and when splicing.

var array1 = ['fred', 'sue'];
var array2 = ['sue'];
modified = [];

array1.forEach(function(element) {
  var index = array2.findIndex(el => el.startsWith(element[0]));
  if (index > -1) {
    modified.push(array2[index]);
    array2.splice(index, 1);
  } else {
    modified.push(element);
  }
});

console.log(modified);

  • 发表于 2019-03-16 01:50
  • 阅读 ( 219 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除