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

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

问题描述

我需要检查一个 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.

推荐答案

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

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):

const findDuplicates = (arr) => {
  let 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)
  let results = [];
  for (let i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
      results.push(sorted_arr[i]);
    }
  }
  return results;
}

let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);

以防万一,如果您要作为重复项的函数返回.这是针对类似类型的案例.

In case, if you are to return as a function for duplicates. This is for similar type of case.

参考:https://stackoverflow.com/a/57532964/8119511

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

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