Skip to content Skip to sidebar Skip to footer

How To Concatenate Two Strings Without Duplicates In Javascript

I have two strings as below: var str1 = '5YRS,AC,ALAR'; var str2 = 'MON,5YRS,TRAU'; I want to merge these two strings into one string and to remove duplicates in this. I tried the

Solution 1:

You could join the two strings with an array and then split the values for getting unique results from a Set.

var str1 = "5YRS,AC,ALAR",
    str2 = "MON,5YRS,TRAU",
    joined = Array.from(newSet([str1, str2].join(',').split(','))).join(',');

console.log(joined);

Solution 2:

You can use Set to avoid duplicates:

var str1 = "5YRS,AC,ALAR";
var str2 = "MON,5YRS,TRAU";
var res = [...newSet([...str1.split(','), ...str2.split(',')])].join(',');
console.log(res);

OR:

var str1 = "5YRS,AC,ALAR";
var str2 = "MON,5YRS,TRAU";
var res = [...newSet(str1.split(',').concat(str2.split(',')))].join(',');
console.log(res);

Post a Comment for "How To Concatenate Two Strings Without Duplicates In Javascript"