本文介绍了在 JavaScript 中获取两个数组的并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 [34, 35, 45, 48, 49] 数组和另一个 [48, 55] 数组.如何获得 [34, 35, 45, 48, 49, 55] 的结果数组?

Say I have an array of [34, 35, 45, 48, 49] and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?

推荐答案

如果不需要保留顺序,可以考虑45"45"保持不变:

If you don't need to keep the order, and consider 45 and "45" to be the same:

function union_arrays (x, y) {
  var obj = {};
  for (var i = x.length-1; i >= 0; -- i)
     obj[x[i]] = x[i];
  for (var i = y.length-1; i >= 0; -- i)
     obj[y[i]] = y[i];
  var res = []
  for (var k in obj) {
    if (obj.hasOwnProperty(k))  // <-- optional
      res.push(obj[k]);
  }
  return res;
}

console.log(union_arrays([34,35,45,48,49], [44,55]));

这篇关于在 JavaScript 中获取两个数组的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 10:27