在 Javascript 中删除数组中的重复项
var data = localStorage.getItem('oldData').split(" ");
我正在如上所述访问 localStorage 并获取一组值。有些元素在 oldData
的字符串值中重复,例如:
apples oranges apples apples
我希望数据只有两个元素 apples
和 oranges
。我怎样才能在 JavaScript 中做到这一点?
var data = localStorage.getItem('oldData').split(" ");
I am accessing localStorage as above and getting an array of values. Some of the elements are repeated in the string value for oldData
, for example:
apples oranges apples apples
I want data to have only two elements apples
and oranges
. How can I do this in Javascript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
系上它。它的复杂度为 O(n),因为使用对象只需要您循环遍历数组一次并将其中的每个值分配为键,然后进行覆盖。仅当值是基元时(或者您有 Harmony WeakMap),这才有效。但这几乎总是你想要做的数组类型,这样它就可以成功。
对于奖励积分,这是第二种最佳方法。这至少是正常双循环答案的两倍,并且至少与需要预排序的答案一样好,
(但仍然比上面的哈希方法差,它无限快)。
它击败除哈希之外的所有其他答案的原因是因为它能够在不执行排序步骤的情况下获得排序的好处。它只从当前项向前查找,从另一端反向查找,因此永远不会出现两个项相互检查两次的情况,也永远不会进行不必要的比较,因为它总是在最开始就退出。做出最终决定所需的最少工作量。作为奖励,它通过尽可能少地创建占位符变量来完成所有这一切。
Strap it on. It's O(n) because using an object just requires you to loop through the array once and assign every value in it as a key, overwriting as you go. This only works when the values are primitives (or you have Harmony WeakMaps). But that's almost always the kind of array you want to do this one so it works out.
For bonus points here's the second best way to do it. This is at minimum twice as fast as the normal double loop answers and is at minimum as good as the ones requiring presorting,
(but still worse than the above hash method which is infinitely faster).
The reason it beats every other answer aside from the hash is because it's able to get the benefit of sorting without doing the sorting step. It only searches from the current item forward, and from the other end in reverse, so there will never be a case where two items are checked against each other twice, and there will never be an unnecessary comparison done because it always quits at the very minimum amount of work needed to make a final decision. And it does all of this with the minimum possible creation of placeholder variables as a bonus.
第一种是使用push在数组中插入一个值
,然后插入下一个值,使用“for循环”检查数组中是否存在您的值。然后如果该值不存在,则再次使用push()插入该值
first is to insert one value in your array by using push
then the next insertion of value, check if your value is existing in your array using "for loop". then if the value does not exist, insert that value using push() again
像这样的事情应该可以解决问题:
Something like this should do the trick:
这是我最后用的
This is what I have used finally