最简单的方式找到一个JavaScript数组中重复的值 [英] Easiest way to find duplicate values in a JavaScript array

查看:127
本文介绍了最简单的方式找到一个JavaScript数组中重复的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查JavaScript数组,看看是否有任何重复的值。怎样做最简单的方法?我只需要查找重复的值是 - 我实际上并不需要他们的索引或者他们有多少次重复

我知道我可以通过数组循环,并检查所有其他值匹配,但是看起来应该有一个更简单的方法。有任何想法吗?谢谢!

相关报道:取下JavaScript的数组重复


解决方案

您可以在数组进行排序,然后通过运行它,然后看看下一个(或previous)指数相同的电流。假设你的排序算法是好的,这应该是小于为O(n 2

\r
\r

VAR ARR = [9,9,111,2,3,4,4 ,5,7];\r
VAR sorted_arr = arr.slice()排序()。 //你可以在这里定义比较功能。\r
                                     // JS默认使用一个蹩脚的字符串进行比较。\r
                                     //(我们使用切片克隆阵列所以原始数组不会被修改)\r
变种结果= [];\r
对于(VAR I = 0; I< arr.length - 1;我++){\r
    如果(sorted_arr第[i + 1] == sorted_arr [I]){\r
        results.push(sorted_arr [I]);\r
    }\r
}\r
\r
警报(结果);

\r

\r
\r

I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.

I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way. Any ideas? Thanks!

Related: Remove Duplicates from JavaScript Array

解决方案

You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.slice().sort(); // You can define the comparing function here. 
                                     // JS by default uses a crappy string compare.
                                     // (we use slice to clone the array so the original array won't be modified)
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        results.push(sorted_arr[i]);
    }
}

alert(results);

这篇关于最简单的方式找到一个JavaScript数组中重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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