Home > Blockchain >  Optimal function javascript to eliminate duplicates
Optimal function javascript to eliminate duplicates

Time:05-04

So let's say i have a variable that stores a big string and where the
is the separator to the next word. whats the best way to eliminate duplicate words using the
as the indicator.

So imagine we have this:

var notRemoved= " I am col 1 
I am col 2
I am col 11 
I am col 1 
I am col 2

And the result should be like this:

var removed= " I am col 1 
I am col 2
I am col 11 "

CodePudding user response:

This one has answer here : Get all unique values in a JavaScript array (remove duplicates)

Try this:

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);

console.log(unique); // ['a', 1, 2, '1']

CodePudding user response:

The best way to perfom what you want is by :

  • Splitting your String into an array
  • Removing the duplicates (for example using a Set)
  • Re-creating a string using the join method.

const notRemoved = `I am col 1 
I am col 2
I am col 11 
I am col 1 
I am col 2`



function removeDuplicatesFromString(str){
  const splitArray = notRemoved.split('\n')
  const arrayWithoutDuplicates = [...new Set(splitArray)];

  return arrayWithoutDuplicates.join('\n')
}


console.log(removeDuplicatesFromString(notRemoved))

Note : This can also be done using one line :

let removed = [...new Set(notRemoved.split('\n')].join('\n');

Documentation

split method

Set

join method

  • Related