【问题标题】:How to identify which elements are missing from an incomplete array, given a complete array?给定一个完整数组,如何识别不完整数组中缺少哪些元素?
【发布时间】:2020-11-22 12:48:00
【问题描述】:

我正在尝试为这个问题编写一个功能解决方案。我已经有一个解决方案,它使用循环和突变而不使用递归(我知道我在下面尝试的涉及突变,我试图避免这种情况)。

请在下面的 cmets 中查看预期输出。我要强调的是,元素不一定是唯一的,排序无关紧要。

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' ]

【问题讨论】:

    标签: javascript arrays functional-programming purely-functional


    【解决方案1】:

    您可以执行以下操作:

    const namesArrayWithHoles = ['Bob', null, null, 'Sue', null];
    const namesArrayFilled = ['Jim', 'Bob', 'Bob', 'Sam', 'Sue'];
    
    const result = namesArrayFilled.reduce(
      (acc, elem) => {
        const index = acc[0].indexOf(elem);
        if (index != -1) {
          return [acc[0].slice(0, index).concat(acc[0].slice(index + 1)), acc[1]];
        }
        return [acc[0], acc[1].concat(elem)];
      },
      [namesArrayWithHoles, []]
    )[1];
    
    console.log(result);

    【讨论】:

    • 由于(index = ,您的代码无法在严格模式下运行?
    • 我什至尝试过(let index =,但它抱怨意外的保留字。
    • @GirkovArpa 哦,我通过为index 添加const 解决了这个问题。谢谢!
    【解决方案2】:

    我找到了这个解决方案。它确实假设没有 null 值,因为那只是分散注意力。

    const getMissingValues = (partial, complete) => {
      const equals = a => b => b == a;
      const push = (arr, val, count) => count ? push([...arr, val], val, count - 1) : [...arr];
      return [...new Set(complete)].reduce((missing, val) => {
        const { length: a } = partial.filter(equals(val));
        const { length: b } = complete.filter(equals(val));
        const diff = (b - a);
        return push(missing, val, diff);
      }, []);
    }
    
    const partial = ['Bob', 'Sue'];
    const complete = ['Jim', 'Bob', 'Bob', 'Bob', 'Sue', 'Sue', 'Sam'];
    const missing = getMissingValues(partial, complete);
    
    console.log(missing); // [ 'Jim', 'Bob', 'Bob', 'Sue', 'Sam' ]

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 2018-12-03
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多