关于javascript:将多个数组Concat分成一个没有重复的数组

Concat multiple arrays into one array without duplicates

本问题已经有最佳答案,请猛点这里访问。

我想在新数组中推送3个数组的值,而不重复相同的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var a = ["1","2","3"];
var b = ["3","4","5"];
var c = ["4","5","6"];
var d = [];

function newArray(x, y, z) {
    for(var i = 0; i < d.length; i++) {
        if(d.length == -1) {
            d[i].push(a[i])
        }
    }

    for(var i = 0; i < d.length; i++) {
        if(d.length == -1) {
            d[i].push(y[i])
        }
    }

    for(var i = 0; i < d.length; i++) {
        if(d.length == -1) {
            d[i].push(z[i])
        }
    }
}

newArray(a, b, c);

d = ["1","2","3","4","5","6"];


如果您的目标是删除重复项,则可以使用集合,

1
2
3
4
var arr = [1,2,3,4,5,5,6,6,6,7]
var mySet = new Set(arr)
var filteredArray = Array.from(mySet)
filteredArray.sort() // [1,2,3,4,5,6,7]

您可以同时使用concat()Set,如下所示:

1
2
3
4
5
6
7
8
9
10
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
2
3
4
5
6
7
8
9
10
11
12
13
14
var a = ["1","2","3"]
  , b = ["3","4","5"]
  , c = ["4","5","6"]
  , d = [];

function newArray(x,y,z) {
  x.concat(y,z).forEach(item =>{
     if (d.indexOf(item) == -1)
       d.push(item);
  });
  return d;
}

console.log(newArray(a,b,c));


您可以使用非常有用的实用程序库lodash来节省一些时间和精力。

你要找的功能是联合

如罗达什所述:

Creates an array of unique values, in order, from all given arrays
using SameValueZero for equality comparisons.

例子

1
2
_.union([2], [1, 2]);
// => [2, 1]

这是另一个版本:

1
2
3
4
5
6
var d = b.concat(c);
  d.forEach(function(el) {
    if (a.indexOf(el) === -1) {
    a.push(el)
  }
})

ES6版本:

1
2
3
4
5
6
let d = b.concat(c);
d.forEach(el => {
  if (a.indexOf(el) === -1) {
    a.push(el)
  }
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var a = ["1","2","3"];
var b = ["3","4","5"];
var c = ["4","5","6"];

var d = [];

var hash = [];
AddToHash(a);

AddToHash(b);

AddToHash(c);

function AddToHash(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (!hash[arr[i]]) {
      hash[arr[i]] = 1;
    } else
      hash[arr[i]] += 1;
  }
}

for (var i = 0; i < hash.length; i++) {
    d.push(i);
}
console.log(d);

希望这有帮助