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

Sign up to request clarification or add additional context in comments.

8 Comments

nice answer, although I'd probably make the default parameter to join explicit (for readability)
As we've seen before, the problem is simple and this is a duplicate. Close-vote it instead.
@Cerbrus, good morning. i was waiting for you ;-)
I don't get it. Why do you even answer questions like these? For the easy rep?
@Cerbrus It's not a duplicate. It's about merging string, not array
|
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.