JavaScript Exercises Basic#17 - Remove Repeated String from Multiple Strings
You will be given multiple strings in an array. Write a program to return array without repeated elements.
Result Example
Solution
- Iterate through the given array.
- We are going to use filter() method to make a new array without repeated elements. Inside the filter, define a function and get the index of each string elements using indexOf() method.
- If the original index of each elements(arr.indexOf(v)) differs from the current index(i), it means there was a duplicate. The filter method will return a new array without the duplicates.
- Return answer array.
function removeDuplicates(arr){
let answer;
answer = arr.filter((v, i) => {
if(arr.indexOf(v) === i) return v;
});
return answer;
}