Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an array which looks like this:
["A", "A", "A", "A", "B", "B", "B", "C", "C", "D", "A", "A", "B", "B", "B"]

How can I filter it, so there is only one unique value at a time, like this:
JavaScript
['A', 'B', 'C', 'D', 'A', 'B']


What I have tried:

I have tried two different approaches, I decided to use a for loop first
JavaScript
function uniqueInOrder(arg) {
  var arr = [];
   arg.split('');
  for(var i = 0; i < arg.length; i++){
    if(arg[i] === arg[i+1]) {arr.push(arg[i])}
    
  }
 return arr
}

But as far as I understand, I would need to disable it somehow from pushing if it already found the duplicate, because I get this output:
["A", "A", "A", "B", "B", "C", "A", "B", "B"]

Also, I tried this method:
array.filter(function (value, index, self) { 
    return self.indexOf(value) === index;
})

But that just doesn`t allow duplicates
Posted
Updated 13-Aug-16 10:40am

1 solution

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

Try
JavaScript
if(arg[i] != arg[i+1]) {arr.push(arg[i])}

it should be better, even if there is more bugs.
 
Share this answer
 
Comments
AlexLearne 13-Aug-16 17:15pm    
Thank you a lot for your answer, I think you have already told me about using the debugger and I do want to learn it but I have some questions and I tried to ask them but unfortunately my comment was left unnoticed by you.
Of course, I can google them and I am sure I will find lots of answers but I would like to learn from somebody who is experienced as you are.
1. Do you personally use Visual Studio Debugger?
2. What about debugging right in the console? Is it worse? Is it too difficult for a beginner like me?
3. How did you learn to debug?
Any tips will be very appreciated. And again, I am very grateful for your help!
Patrice T 13-Aug-16 17:37pm    
1) No
2) For JS your browser have a debugger.
3) Practicing is the only way. It is not so complicated.

you have 2 links in the solution.
Don't hesitate to Google
AlexLearne 14-Aug-16 7:16am    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900