Reputation: 15
Hi I have a quick question
I am trying to make a function that takes a string input "aacbdgtg"
and have it output an array like so:
[["a", 2], ["c", 1], ["b", 1], ["d", 1], ["g", 2], ["t", 1]]
So far I have written
var hist = function(string) {
var result = [];
for(var i = 0; i < string.length; i++) {
if (result.length === 0) {
result.push([string[i], 1]);
}
else {
for (var j = 0; j < result.length; j++) {
if (string[i] === result[j][0]) {
result[j][1]++;
}
}
result.push([string[i], 1]);
}
}
return result;
};
And i get a result of
[["a", 2], ["a", 1], ["c", 1], ["b", 1], ["d", 1], ["g", 2], ["t", 1], ["g", 1]]
Any help would be great thank you as I cam stuck and need help, I am not sure how to check if an array already has another array with the same letter
For example I don't know how to check if [["a", 2], ["a", 1]] has already used the letter "a"
Upvotes: 0
Views: 171
Reputation: 115222
Better way is to create an object first afterwards create the array structure using it. Also you can use reduce()
method here.
var hist = function(str) {
var result = [],
temp;
// generate the object which holds string count
temp = str.split('').reduce(function(a, b) {
a[b] = a[b] + 1 || 1;
return a;
}, {});
// generate the result using the object
var result = Object.keys(temp).map(function(v) {
return [v, temp[v]];
});
return result;
};
document.write('<pre>' + JSON.stringify(hist('aacbdgtg')) + '</pre>');
Of using simple for loop only
var hist = function(str) {
var result = [],
temp = {},
strArr = str.split('');
// generate the object which holds string count
for (var i = 0; i < strArr.length; i++) {
temp[strArr[i]] = temp[strArr[i]] + 1 || 1;
}
// generate the result using the object
var keys = Object.keys(temp);
for (var i = 0; i < keys.length; i++) {
result.push([keys[i], temp[keys[i]]]);
}
return result;
};
document.write('<pre>' + JSON.stringify(hist('aacbdgtg')) + '</pre>');
Upvotes: 2