创建作为函数参数给出的数组联合

时间:2017-10-28 03:50:37

标签: javascript

我想创建一个作为函数参数给出的数组联合。但我有这个错误:

Javascript TypeError: Cannot read property 'length' of undefined

这就是我想要做的事情:

function uniteUnique(arr) {

  var newArr = arguments[0];

  //Loop arguments
  for (let i = 0; i<arr.length-1; i++){
    console.log(arguments[i]);

    //Loop second argument values
    for (let y =0; y<arguments[i+1].length; y++){

      //Loop first argument values
      for (let z=0; z<arguments[i].length; z++){
        if (arguments[i+1][y] !== arguments[i][z]){
          newArr.push(arguments[i+1][y]);
        }

      }
    }
  }
  return arr;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

我想要的输出是[1,3,2,5,4],这是这里3个数组的唯一值的并集。我收到了这个错误。

  

TypeError:无法读取未定义的属性“length”

2 个答案:

答案 0 :(得分:1)

从我可以理解你想要将三个数组合并为一个删除重复项。然后以下代码将帮助您。

var a = ["1","2","3"];
var b = ["3","4","5"];
var c = ["4","5","6"];

var d = a.concat(b).concat(c);
var set = new Set(d);

d = Array.from(set);

console.log(d);

答案 1 :(得分:1)

使用ES6 features

function unionArg(...args){
let newtab = []

//Destructuring of each arg which is an array
args.forEach(arg=>{
  newtab = [...arg,...newtab]
})

//Having all the items in a single array, we will keep only distincts elements
newtab = [...new Set(newtab)]

console.log("unique values:" + newtab)

}

unionArg([1,2,3,1],[0,4,1])