Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

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

I need to check a JavaScript array to see if there are any duplicate values.(我需要检查一个JavaScript数组,看看是否有重复的值。)

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.(我知道我可以遍历数组并检查所有其他值是否匹配,但是似乎应该有一种更简单的方法。) Similar question:(类似的问题:) Get all unique values in a JavaScript array (remove duplicates)(获取JavaScript数组中的所有唯一值(删除重复项))   ask by Scott Saunders translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(n 2 ):(假设您的排序算法很好,则该值应小于O(n 2 ):) 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); In case, if you are to return as a function for duplicates.(以防万一,如果要作为重复函数返回。) This is for similar type of case.(这是类似情况。) Reference: https://stackoverflow.com/a/57532964/8119511(参考: https : //stackoverflow.com/a/57532964/8119511)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...