我正试图为这个问题写一个实用的解决方案。我已经有了一个解决方案,它使用循环和无递归的变异(我知道我下面尝试的是变异,我正试图避免这种情况)。
请在下面的注释中查看预期输出。我要强调的是,元素不一定是唯一的,排序也不重要。
const getNamesWhichFillHoles = (namesArrayWithHoles, namesArrayFilled, fillers = []) => {
const holey = [...namesArrayWithHoles].filter(Boolean);
const filled = [...namesArrayFilled].filter(Boolean);
const fillerIndexInFilled = filled.findIndex(name => !holey.includes(name));
if (fillerIndexInFilled === -1) return fillers;
const filler = filled[fillerIndexInFilled];
const fillerIndexInHoley = holey.findIndex(name => name == filler);
fillers.push(filler);
filled[fillerIndexInFilled] = null;
holey[fillerIndexInHoley] = null;
return getNamesWhichFillHoles(holey, filled, fillers);
}
const namesArrayWithHoles = ['Bob', null, null, 'Sue', null];
const namesArrayFilled = ['Jim', 'Bob', 'Bob', 'Sam', 'Sue',];
const fillerNames = getNamesWhichFillHoles(namesArrayWithHoles, namesArrayFilled);
console.log(fillerNames); // [ 'Jim', 'Sam' ]
// should be: [ 'Jim', 'Sam', 'Bob' ]