获取数组中的所有非唯一值(即:重复/多次出现) [英] Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

查看:118
本文介绍了获取数组中的所有非唯一值(即:重复/多次出现)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查JavaScript数组以查看是否存在任何重复值。最简单的方法是什么?我只需要找到重复的值是什么 - 我实际上并不需要它们的索引或重复它们的次数。

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!

  • Get all unique values in an array (remove duplicates)

推荐答案

您可以对数组进行排序,然后运行它,然后查看下一个(或上一个)索引是否与当前索引相同。假设您的排序算法很好,这应该小于O(n 2 ):

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 < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        results.push(sorted_arr[i]);
    }
}

console.log(results);

这篇关于获取数组中的所有非唯一值(即:重复/多次出现)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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