Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat multiple arrays into one array without duplicates [duplicate]

Tags:

javascript

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"];
like image 200
Raheel Nawab Avatar asked Nov 06 '16 23:11

Raheel Nawab


People also ask

Does array concat remove duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates.

How do you merge two arrays of objects in JavaScript and de duplicate items?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.


2 Answers

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]
like image 58
chatton Avatar answered Oct 14 '22 15:10

chatton


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);
like image 25
Aruna Avatar answered Oct 14 '22 16:10

Aruna