Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
I was trying to merge two JavaScript arrays and I want to get the output as no duplicates record. Can anyone help me with this?

1 Answer

0 votes
by (26.7k points)

If you want to merge the arrays, you can use the following code:

var array1 = ["Vijendra", "Singh"];

var array2 = ["Singh", "Shakya"];

console.log(array1.concat(array2));

If you want to remove the duplicates, you can prefer the below code:

function arrayUnique(array) {

    var a = array.concat();

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

        }

    }

    return a;

}

var array1 = ["Vijendra","Singh"];

var array2 = ["Singh", "Shakya"];

    // Merges both arrays and gets unique items

var array3 = arrayUnique(array1.concat(array2));

I hope this will help.

Want to become a Java Expert? Join Java Course now!!

Related questions

0 votes
1 answer
asked Mar 17, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+1 vote
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...