Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get distinct values from comma separated string in javascript, use split(",") with ...new Set() spread operator it will return array of unique values then use join() method it will return distinct values from comma separated string.

Let’s see a short example of javascript remove duplicate values from comma-separated strings.

const string = "infinitbility,aguidehub,sortoutcode,aguidehub,sortoutcode,infinitbility,sortoutcode";
const strArr = string.split(",");
const uniqueArray = [...new Set(strArr)];

console.log(uniqueArray)

Today, I’m going to show you How do I get distinct values from comma separated string in javascript, as above mentioned, I’m going to use the above-mentioned combination of split(",") with ...new Set() spreed operator and join() method.

Let’s start today’s tutorial on how do you get distinct values from comma-separated strings in javascript.

Javascript gets distinct values from comma-separated string

Here, we will do

  1. Take a sample comma-separated string
  2. Create array of it using split(",") method
  3. Use ...new Set() to remove duplicates values
  4. Use the join() method to re-create comma separate string
// Take sample comma separated string
const string = "infinitbility,aguidehub,sortoutcode,aguidehub,sortoutcode,infinitbility,sortoutcode";

// Create array of it using `split(",")` method
const strArr = string.split(",");

// Use `...new Set()` to remove dublicates values
const uniqueArray = [...new Set(strArr)];

// Use `join()` method to re-create comma seprated string
const newString = uniqueArray.join();

console.log("strArr: ", strArr)
console.log("uniqueArray: ", uniqueArray)
console.log("newString: ", newString)

// Output:
// strArr:  [
//   'infinitbility',
//   'aguidehub',
//   'sortoutcode',
//   'aguidehub',
//   'sortoutcode',
//   'infinitbility',
//   'sortoutcode'
// ]
// uniqueArray:  [ 'infinitbility', 'aguidehub', 'sortoutcode' ]
// newString:  infinitbility,aguidehub,sortoutcode

Output

I hope it helps you, All the best đź‘Ť.