17

I want to push values of 3 arrays in 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"];
Raheel Nawab
  • 173
  • 1
  • 1
  • 4

6 Answers6

12

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]
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
chatton
  • 596
  • 1
  • 3
  • 8
  • 1
    Works pretty well also in one line with `concat` for appending `arr2` to `arr1`: `arr1 = Array.from(new Set(arr1.concat(arr2)));` – Patrizio Bekerle Jun 30 '21 at 08:20
12

You can use concat() and Set together as below,

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);
Aruna
  • 11,959
  • 3
  • 28
  • 42
3

You could save yourself some time and effort with the very useful utility library Lodash.

The function you're looking for is Union

As stated by Lodash:

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

Example

_.union([2], [1, 2]);
// => [2, 1]
Kevin
  • 1,219
  • 1
  • 16
  • 34
2

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));
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
0

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

Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
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)
  }
})
Falk
  • 627
  • 5
  • 12