简体   繁体   中英

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:

 var foo = ['1X31UX11','X3U11X1','33X11U12', '1X31UX11']; var result = foo.reduce(function(count, str) { count[str] = (count[str] || 0) + 1; return count; }, {}); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM