Last active
August 29, 2015 14:06
-
-
Save loonison123/c7379fe198e47b9de929 to your computer and use it in GitHub Desktop.
Finding duplicates in JavaScript array of strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Some sample data | |
| var image1 = { name: 'google1', ext: 'jpg', url: '/some/url.jpg', tags: ['red', 'pants', 'jeans'] }; | |
| var image2 = { name: 'apple5', ext: 'png', url: '/some/url.png', tags: ['red', 'black', 'jeans'] }; | |
| var image3 = { name: 'nexus7', ext: 'png', url: '/some/url.png', tags: ['black', 'pants', 'jeans', 'jeans'] }; | |
| // Tags for an image can have NO duplicate tags | |
| image1.tags = _.uniq(image1.tags); image2.tags = _.uniq(image2.tags); image3.tags = _.uniq(image3.tags); | |
| var images = []; | |
| images.push(image1); images.push(image2); images.push(image3); | |
| // Array has duplicates, which is ok | |
| // i.e.--> ["red", "pants", "jeans", "red", "black", "jeans", "black", "pants", "jeans"] | |
| var allTags = []; | |
| for (var i=0; i<images.length; i++) { | |
| var image = images[i]; | |
| for (var j=0; j<image.tags.length; j++) { | |
| allTags.push(image.tags[j]); | |
| } | |
| } | |
| var cached = {}; // Used to know if we have already added the tab | |
| var duplicatedTags = []; | |
| for (var i=0;i<allTags.length; i++) { | |
| if (cached[allTags[i]] == undefined) { | |
| // If undefined, then it's safe to add. It hasn't been added before | |
| cached[allTags[i]] = allTags[i]; | |
| if (hasDup(allTags, allTags[i], allTags.length)) { | |
| duplicatedTags.push(allTags[i]); | |
| } | |
| } | |
| } | |
| // duplicatedTags now contains ["jeans"] | |
| // You know that the 3 images you selected to edit tags all contain 'jeans' as a tag | |
| console.log(duplicatedTags); | |
| // arr - source array that contains all our data | |
| // val - the value we are checking for dupes i.e. 'pants', 'shirts' | |
| // greaterThan - this is the amount that has to be duplicated for the value to be recorded | |
| // i.e. if 3 images are selected, then this would be 3. 3 images need to have the same tag | |
| function hasDup(arr, val, greaterThan) { | |
| // Count for 1 item (tag) | |
| var count = 0; | |
| for (var i = 0; i < arr.length; i++) { | |
| // Every time a match is found we increment our count that will say how many exist | |
| if (arr[i] == val) | |
| count++; | |
| } | |
| // You have to have as many duplicates as images so the tag exists in all of them | |
| if (count >= greaterThan){ | |
| return true; | |
| } | |
| return false; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment