1

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 below method:

var main_str = str1.concat(str2) //result: "5YRS,AC,ALARMON,5YRS,TRAU"

Result which i got is getting merged at on end and if i push any string dynamically it is not showing the desired result. Is there any new ES6 implementation to get a method which checks both null check and return unique string values.

1
  • 2
    a string by itself has no concept of "duplicates" - you have to break the string up into words first.
    – Alnitak
    Commented Aug 9, 2018 at 9:54

2 Answers 2

6

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(new Set([str1, str2].join(',').split(','))).join(',');

console.log(joined);

8
  • nice answer, although I'd probably make the default parameter to join explicit (for readability)
    – Alnitak
    Commented Aug 9, 2018 at 9:59
  • 2
    As we've seen before, the problem is simple and this is a duplicate. Close-vote it instead.
    – Cerbrus
    Commented Aug 9, 2018 at 10:07
  • @Cerbrus, good morning. i was waiting for you ;-) Commented Aug 9, 2018 at 10:08
  • I don't get it. Why do you even answer questions like these? For the easy rep?
    – Cerbrus
    Commented Aug 9, 2018 at 10:08
  • @Cerbrus It's not a duplicate. It's about merging string, not array
    – Faly
    Commented Aug 9, 2018 at 10:18
1

You can use Set to avoid duplicates:

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

OR:

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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.