EDIT:
The first solution is the fastest only when there isare few items. When there isare over 400 items, the Set
solution becomes the fastest. And when there isare 100,000 items, it is a thousand times faster than the first solution.
Considering that performance is important only when there is a lot of items, and that the Set
solution is by far the most readable, it should be the right solution in most cases
The perf results below were computed with a small number of items
Based on jsperf, the fastest way (edit: if there isare less than 400 items) to merge two arrays in a new one is the following:
for (var i = 0; i < array2.length; i++)
if (array1.indexOf(array2[i]) === -1)
array1.push(array2[i]);
This one is 17% slower:
array2.forEach(v => array1.includes(v) ? null : array1.push(v));
This one is 45% slower (edit: when there is less than 100 items. It is a lot faster when there is a lot of items):
var a = [...new Set([...array1 ,...array2])];
And the accepted answersanswer's is 55% slower (and much longer to write) (edit: and it is several order of magnitude slower than any of the other methods when there isare 100 000,000 items)
var a = array1.concat(array2);
for (var i = 0; i < a.length; ++i) {
for (var j = i + 1; j < a.length; ++j) {
if (a[i] === a[j])
a.splice(j--, 1);
}
}
https://jsperf.com/merge-2-arrays-without-duplicatehttps://jsbench.me/lxlej18ydg