[英]Find and return exact matches (duplicates) in Javascript Array
So I've been googling a lot and tried to use different filters for arrays and such, to no avail. 因此,我一直在大量搜索,并尝试对数组使用不同的过滤器,但无济于事。
I have an array with a string like so: 我有一个像这样的字符串数组:
var foo = ['1X31UX11','X3U11X1','33X11U12'];
Is there a way to check every string against each other in the array, and if there's an exact match (ie the exact same order of characters) it prints how many times the particular string occurs & also prints the string in question? 有没有一种方法可以检查数组中每个字符串是否相互匹配,并且如果存在完全匹配(即完全相同的字符顺序),它将打印出特定字符串出现了多少次并还打印了相关字符串?
function arrayRepeats(array) { var returnObject = {}; for (var i = 0; i < array.length; i++) { if (returnObject[array[i]]) { returnObject[array[i]]++; } else { returnObject[array[i]] = 1; } } return returnObject; } var foo = ['1X31UX11','X3U11X1','33X11U12']; console.log(arrayRepeats(foo)); var bar = [1, 1, 2, 1, 3, 1, 31, 3, 1, 5, 4, 1]; console.log(arrayRepeats(bar));
Use Array#reduce to collect the the number of appearances of each string into an object: 使用Array#reduce收集每个字符串出现在一个对象中的数量:
var foo = ['1X31UX11','X3U11X1','33X11U12', '1X31UX11']; var result = foo.reduce(function(count, str) { count[str] = (count[str] || 0) + 1; return count; }, {}); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.