Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to remove duplicate strings in an array

We have managed to create the script below to remove any duplicate strings from an array. However, it is important that we keep the order of the array for when angular loops through them on an ng-repeat. In addition, we want the remaining elements to keep the same index.

scope.feedback = _.map(_.pluck(item.possibleAnswers, 'feedback'), function (element, index, collection) {
    return collection.slice(0, index).indexOf(element) === -1 ? element : '';
});

This code above works however we feel like there must be a more simple solution to our problem than this. Has anyone else had a similar problem and come up with a better solution?

like image 409
Max Lynn Avatar asked Jul 14 '16 11:07

Max Lynn


People also ask

How do I remove duplicates from a string array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

Which function removes duplicate values from an array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

How do you prevent duplicates in an array?

To prevent adding duplicates to an array: Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.


3 Answers

Variant with reduce https://jsfiddle.net/58z7nrfy/1/

var a = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];

var b = a.reduce(function(p,c,i,a){
  if (p.indexOf(c) == -1) p.push(c);
  else p.push('')
  return p;
}, [])
console.log(b)

[1, 2, 3, "", "", "", "", "", "", 4, 5, "", 12, "", 23, "", ""]

like image 200
llamerr Avatar answered Nov 15 '22 02:11

llamerr


Apart from the answers mentioned, you can also use lodash union function like this:

let duplicates = ['Hello', 'Hi', 'Hello'];
let uniques = _.union(duplicates);

Uniques will be: ["Hello", "Hi"]

like image 38
Himanshu Tanwar Avatar answered Nov 15 '22 03:11

Himanshu Tanwar


If the target browsers support spread operator then try in your console:

[...new Set(['3','1','1','5'])]
// ['3','1','5']

Or if browser support Array.from you could also write:

Array.from(new Set(['3','1','1','5']))
// ['3','1','5']
like image 42
bjaksic Avatar answered Nov 15 '22 02:11

bjaksic