过滤数组以显示唯一值javascript [英] Filter an array to display unique values javascript

查看:114
本文介绍了过滤数组以显示唯一值javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组:

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:

['A', 'B', 'C', 'D', 'A', 'B']





什么我试过了:



我尝试了两种不同的方法,我决定先使用for循环



What I have tried:

I have tried two different approaches, I decided to use a for loop first

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
}



但据我所知,我需要以某种方式禁用它,如果它已经找到了副本,因为我得到了这个输出:

[A, A,A,B,B,C,A,B,B]



此外,我试过这个方法:


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

推荐答案

你应该学会使用调试器尽快地。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候你接近一个bug。



试试

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
if(arg[i] != arg[i+1]) {arr.push(arg[i])}



它应该是更好,即使有更多的错误。


it should be better, even if there is more bugs.


这篇关于过滤数组以显示唯一值javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆