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.

tracer
  • 422
  • 2
  • 7
  • 15
  • 2
    a string by itself has no concept of "duplicates" - you have to break the string up into words first. – Alnitak Aug 09 '18 at 09:54

2 Answers2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • nice answer, although I'd probably make the default parameter to `join` explicit (for readability) – Alnitak Aug 09 '18 at 09:59
  • 2
    As we've seen before, the problem is simple and this is a duplicate. Close-vote it instead. – Cerbrus Aug 09 '18 at 10:07
  • @Cerbrus, good morning. i was waiting for you ;-) – Nina Scholz Aug 09 '18 at 10:08
  • I don't get it. Why do you even answer questions like these? For the easy rep? – Cerbrus Aug 09 '18 at 10:08
  • @Cerbrus It's not a duplicate. It's about merging string, not array – Faly Aug 09 '18 at 10:18
  • @Faly: The only way to do so is to convert the strings to arrays first... The dupe targets answer this question. – Cerbrus Aug 09 '18 at 10:19
  • @Cerbrus the question is clearly stated about string manipulation, dynamic entry and duplicates handling using es6. while i drop in the question i have checked it and put it. – tracer Aug 09 '18 at 10:27
  • @tracer: The answers of the dupes are also about _"manipulation, dynamic entry and duplicates handling"_. The only ES6 method used here is also available in the dupe target. – Cerbrus Aug 09 '18 at 10:28
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);
Faly
  • 13,291
  • 2
  • 19
  • 37