合并两个数组,使原始数组中不存在的值被删除。

huangapple go评论82阅读模式
英文:

Merging two arrays together so that non existing values dropped from original

问题

我可以帮你创建一个合并两个数组的算法,满足以下条件:

  • 删除结果数组中不在替换数组中的值
  • 如果原始数组中不存在某个值,将其添加到结果数组中
  • 不添加重复的值
  • 原始数组和替换数组的大小可以不相同

以下是一个可能的merge函数示例:

function merge(originalArray, replacingArray) {
  // 创建一个新的结果数组,初始化为原始数组的副本
  let result = originalArray.slice();

  // 遍历替换数组
  for (const value of replacingArray) {
    // 如果值在结果数组中不存在,将其添加到结果数组中
    if (!result.includes(value)) {
      result.push(value);
    }
  }

  return result;
}

const originalArray = [1, 2, 3];
const replacingArray = [1, 5, 3, 4];

const result = merge(originalArray, replacingArray);

console.log(result); // [1, 2, 3, 5, 4]

这个merge函数会按照你描述的要求合并两个数组,并返回结果数组。它会删除原始数组中不存在的值,添加替换数组中原始数组中没有的值,并确保不添加重复的值。

英文:

I would like to create an algorithm (or use an existing js library/fn) that would merge two arrays together so that

  • values are dropped from the results that are not in the replacing array compared to original
  • value is added if not exist in the original array
  • duplicates are not added
  • Arrays do not have to be the same size

E.g.

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4]; // 2 is missing and 5,4 are new compared to the original

const result = merge(originalArray, replacingArray); 

console.log(result) // [1,5,3,4]

How could I achieve that? What would be the merge function?

答案1

得分: 1

以下是翻译好的部分:

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4];

const result = [...replacingArray];

如果需要将结果放入originalArray中:

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4];

originalArray.splice(0, originalArray.length, ...replacingArray);
英文:
const originalArray = [1,2,3];
const replacingArray = [1,5,3,4];

const result = [...replacingArray];

The combination of those rules is effectively the same as replacing the original array with the replacement array.

If you need the results to end up in originalArray:

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4];

originalArray.splice(0, originalArray.length, ...replacingArray);

答案2

得分: 0

如果我们应用指定的规则,那么我们就不必做任何复杂的操作,我们只需将replacingArray赋给result数组即可。无论您这样做还是使用一些复杂的函数或算法,结果都将是相同的。

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4]; 

const result = replacingArray;

console.log(result); // [1,5,3,4]
英文:

If we apply the specified rules, then we don't have to do anything complex, we can just assign the replacingArray to the result array. Result will be the same if you do this or use some complex fn or algorithm.

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4]; 

const result = replacingArray;

console.log(result); // [1,5,3,4]

huangapple
  • 本文由 发表于 2023年7月20日 11:51:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定