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"];
1
  • 1
    d = [...new Set([...a, ...b, ...c])]; Commented Nov 7, 2016 at 0:37

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

Works pretty well also in one line with concat for appending arr2 to arr1: arr1 = Array.from(new Set(arr1.concat(arr2)));
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]

Comments

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.