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

Screenshot 2022-04-28 at 18.08.03.png
Solution

  1. Iterate through the given array.
  2. 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.
  3. 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.
  4. Return answer array.
function removeDuplicates(arr){
                let answer;

                answer = arr.filter((v, i) => {
                    if(arr.indexOf(v) === i) return v;
                });

                return answer;
            }