Combining multiple arrays into one array without duplicates

I want to output the values ​​of 3 arrays into a new array without repeating the same values

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"];
+5
source share
6 answers

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));
Run codeHide result
+1
source

If your goal is to remove duplicates, you can use a set

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

+7
source

concat() Set , ,

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);
Hide result
+4

Lodash.

, , Union

Lodash:

, SameValueZero .

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

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);
Hide result

,

0

Here is another version:

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

ES6 Version:

let d = b.concat(c);
d.forEach(el => {
  if (a.indexOf(el) === -1) {
    a.push(el)
  }
})
0
source

Source: https://habr.com/ru/post/1660022/


All Articles