Forked from ralphcrisostomo/array_dupplicate_counter.js
Last active
December 17, 2019 11:40
-
-
Save dreamyguy/82ca233a58f6cff59879f6ce7579f270 to your computer and use it in GitHub Desktop.
Javascript: Count duplicates in an array, ES6
This file contains 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
// Scenario: | |
// You have a javascript array that likely has some duplicate values and you would like a count of those values. | |
const compressArray = arr => { | |
const compressed = []; | |
// make a copy of the input array | |
const copy = arr.slice(0); | |
// first loop goes over every element | |
for (let i = 0; i < arr.length; i++) { | |
let myCount = 0; | |
// loop over every element in the copy and see if it's the same | |
for (let w = 0; w < copy.length; w++) { | |
if (arr[i] === copy[w]) { | |
// increase amount of times duplicate is found | |
myCount++; | |
// sets item to undefined | |
delete copy[w]; | |
} | |
} | |
if (myCount > 0) { | |
const a = {}; | |
a.value = arr[i]; | |
a.count = myCount; | |
compressed.push(a); | |
} | |
} | |
return compressed; | |
}; | |
const testArray = ['dog', 'dog', 'cat', 'buffalo', 'wolf', 'cat', 'tiger', 'cat'];; | |
console.log(compressArray(testArray)); | |
// console output: | |
// [ | |
// { value: 'dog', count: 2 }, | |
// { value: 'cat', count: 3 }, | |
// { value: 'buffalo', count: 1 }, | |
// { value: 'wolf', count: 1 }, | |
// { value: 'tiger', count: 1 } | |
// ] | |
const sorted = compressArray(testArray).sort((a, b) => b.count - a.count); | |
console.log(sorted); | |
// console output: | |
// [ | |
// { value: 'cat', count: 3 }, | |
// { value: 'dog', count: 2 }, | |
// { value: 'buffalo', count: 1 }, | |
// { value: 'wolf', count: 1 }, | |
// { value: 'tiger', count: 1 } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment