Removing Duplicates from the Array
Our Problem
Remove Duplicates from an Array
Create a function that takes an array of items, removes all duplicate items and returns a new array in the same sequential order as the old array (minus duplicates).
Testing:
removeDups([1, 0, 1, 0]) ➞ [1, 0]
removeDups([“The”, “big”, “cat”]) ➞ [“The”, “big”, “cat”]
removeDups([“John”, “Taylor”, “John”]) ➞ [“John”, “Taylor”]
Conditions:
- Test sample contain arrays with both strings and numbers.
- Test samples are case sensitive.
- for above assignment, Try to solve it without using Set
Our Solution
Solution 1
Using plain for loop
function getUnique(arr){
var uniqueArr=[];
for(let i=0;i<arr.length;i++){
if(uniqueArr.indexOf(arr[i]) === -1){
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
Solution 2
Using .forEach
function removeDups(arr) {
var unique = []
arr.forEach(function(val){
if(unique.indexOf(val) < 0){
unique.push(val);
}
});
return unique;
}
Solution 3
Using .reduce() — Advance Level
arr.reduce((acc, curr) => acc.indexOf(curr)< 0?[…acc,curr] : acc, []);
Solution 4
Using .filter() — Advance Level
arr.filter((curr, index) => arr.indexOf(curr) === index);
References
JavaScript Array Iteration
Array iteration methods operate on every array item. The forEach() method calls a function (a callback function) once…
www.w3schools.com
https://www.w3schools.com/js/js_arrays.asp