Reputation: 8165
I am trying to practice my algorithm skills. I know there is already an algorithm written out there, I just want to try it on my own and see how close i could get.
INPUT:
arr1 = ['asd','ew','lol','asd']
EXPECTED OUTPUT:
{ asd: 2, ew: 1, lol: 1 }
This is my code:
arr1 = ['asd', 'ew', 'lol', 'asd']
arr2 = []
results = {}
function checkIfExists(word) {
if (arr2.length != 0) {
for (i = 0; i < arr2.length; i++) {
if (arr2[i] == word) {
results[word] += 1
} else {
arr2.push(word)
results[word] = 1
}
}
} else {
arr2.push(word)
results[word] = 1
}
}
for (i = 0; i < arr1.length; i++) {
checkIfExists(arr1[i])
}
console.log(results)
ACTUAL OUTPUT:
{ asd: 2, ew: 2 }
Upvotes: 0
Views: 68
Reputation: 15642
There are three questions I identified immediately which you might have intended to ask.
The first problem is that you are not using
var
to declarei
.
arr2
also modifies arr2
... a lot!for (i = ...)
to for (var i = ...)
.arr2
, then it shouldn't need to modify arr2
to do so. Perhaps you don't need the loop;
Array.prototype.indexOf
or Array.prototype.includes
in place of that entire loop!function checkIfExists(word) { results[word] = arr1.filter(function(w) { return w === word; }).length; }
in place of that entire function!var arr1 = ['asd','ew','lol','asd'];
var result = arr1.reduce(function(result, w) { result[w] = result[w] || 0;
result[w]++;
return result; }, {}));
console.log(result);
Upvotes: 1
Reputation: 3354
You used i
as a global variable, so don't use for two loop. Other mistake is in your increment algorithm that add more than needed count to results array. So try it:
arr1 = ['asd','ew','lol','asd']
arr2 = []
results = {}
function checkIfExists(word){
if (arr2.length != 0){
var exists = false;
for (var j = 0; j < arr2.length; j++){
if(arr2[j] == word){
results[word] += 1
exists = true;
break;
}
}
if(!exists) {
arr2.push(word)
results[word] = 1
}
}else{
arr2.push(word)
results[word] = 1
}
}
for (var i = 0; i < arr1.length; i++) {
checkIfExists(arr1[i])
}
console.log(results)
Upvotes: 2