Created
January 21, 2023 05:36
-
-
Save cds/fea1d71cab6e9e56a016353f31688693 to your computer and use it in GitHub Desktop.
solution for find count
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
var arr = [1, 2, 3, 3, 3, 4, 3, 5, 4, 6, 5]; | |
//solution with 2 for loop | |
var counts = {}; | |
for (var i = 0; i < arr.length; i++) { | |
for (var j = i; j < arr.length; j++) { | |
if (arr[i] === arr[j]) { | |
if (counts[arr[i]]) { | |
counts[arr[i]]++; | |
} else { | |
counts[arr[i]] = 1; | |
} | |
break; | |
} | |
} | |
} | |
console.log(counts); //Output: { '1': 1, '2': 1, '3': 4, '4': 2, '5': 2, '6': 1 } | |
// solution with single for loop | |
var listCount = {}; // initialize an empty object | |
for (var i = 0; i < arr.length; i++) { | |
var element = arr[i]; | |
if (listCount[element]) { // if element already exists in occArr | |
listCount[element]++; // increment its value | |
} else { | |
listCount[element] = 1; // add the element as a new key-value pair | |
} | |
} | |
console.log(listCount);// output: { '1': 1, '2': 1, '3': 4, '4': 2, '5': 2, '6': 1 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment