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?
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.
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.
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.
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, "", ""]
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"]
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With