r/stackoverflow • • Aug 29 '19

Easy indexOf problem. Help!!

Hi guys, I'm new to the sub, and I need help with a very easy problem. I am currently in a programming 'bootcamp'. If anyone can answer this. Thank you. If anyone can explain it to me. Thanks again. Also I have to use indexOf to solve this, no filter.

Write a function unique(array) that returns an array where all the duplicates

of the input array have been removed; in other words, every element remaining

is unique.

Hint: use indexOf

Example:

unique([1, 1, 2, 3, 3]) => [1, 2, 3]

1 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/xenomachina Aug 30 '19

Here's pseudocode:

  • create an empty array, result. This is our base case.
  • for each item in inputArray:

    • if item isn't already in result, then append it to result
  • return result

Note that this is not the best approach if the array is very large (it's O(n2) time complexity -- if you have 1,000 unique items you're doing on the order of 1,000,000 operations, because indexOf does a linear scan for the item) but it's fine for smallish lists, and I suspect is the answer your instructor was looking for.