Count the numbers in an array then write them out - javascript

It's still old school JS week for newbies at the academy.
I have created an input that makes it possible for a user to put some numbers in a input to write out an array.
Now what I'm trying to do next is writing out a paragraph with a counter for each number, like with how many times the number has been used.
If the array was [0,0,1,1,1,2,2,2,2];
And I want it to write it out something like this:
"How many times does your number appears in your array:"
0: 2
1: 3
2: 4
So far I got it to print out the numbers from the input, but I can't find a way to make it write out like above.
var numbers = [];
function numbarray() {
numbers.push(document.getElementById("box").value);
document.getElementById("text1").innerHTML = "";
document.getElementById("text1").innerHTML += numbers.join(", ");
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
After tinkering, failing and googling since yesterday morning I've figure I try out SO again, since I've learned more from this site then I could ever imagine.
Thank you so much in advance

This solution features an object for counting the frequency of the numbers with a focus of occurrence.
function count() {
var numbers = document.getElementById("box").value
.split(',')
.map(Number)
.filter(isFinite),
distribution = numbers.reduce(function (r, a) {
r[a] = (r[a] || 0) + 1;
return r;
}, {});
document.getElementById("text1").innerHTML = numbers.join(", ");
document.getElementById("distribution").innerHTML = Object.keys(distribution)
.sort(function (a, b) {
return distribution[b] - distribution[a];
})
.map(function (k) {
return k + ': ' + distribution[k];
}).join('<br>');
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="count()" /><br>
Your array: <span id="text1"></span><br>
How many times does your number appears in your array:<br>
<div id="distribution"></div>

var numbers = [];
function numbarray() {
numbers = [];
numbers = numbers.concat(document.getElementById("box").value.split(','));
var hash = {};
for(var i=0; i<numbers.length; i++) {
if (typeof hash[numbers[i]] === 'undefined') hash[numbers[i]] = 0;
hash[numbers[i]] ++;
}
document.getElementById("text1").innerHTML = "";
for(var k in hash) {
document.getElementById("text1").innerHTML += k + ': ' + hash[k] + '\n';
}
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>

function numbarray() {
var nums = {}; // Use a dictionary for tallying numbers
var numStrings = document.getElementById("box").value.split(","); // Split by commas
// Just tally up each number
for (var i = 0; i < numStrings.length; i++){
var num = numStrings[i];
if (num in nums){
nums[num]++;
}
else {
nums[num] = 1;
}
}
var keys_ = Object.keys(nums); // Get the keys and sort them
keys_.sort();
document.getElementById("text1").innerHTML = "<br>"; // Reset the html
for (var key in keys_){
// Print out each number and its tally
document.getElementById("text1").innerHTML = key + ": " + nums[key] + "<br>";
}
}

Not sure if I totally understand what you are trying to do, but if you want to display the count of each number, you should first get the count of each number, then place them in your DOM, through a function such as:
var numbers = [];
var numbersObject = {};
function numbarray() {
numbers.push(document.getElementById("box").value);
//put numbers in object to get count of each
for(i=0; i<numbers.length; i++){
if(numbersObject[numbers[i]]){
numbersObject[numbers[i]]++
}else{
numbersObject[numbers[i]] = 1
}
}
//prepare HTML
var content = '';
for(var key in numbersObject){
content += key + ':' + numbersObject[key] + '<br>';
}
document.getElementById("text1").innerHTML = content
}

Related

How can I extract all contained characters in a String? [duplicate]

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

Why the script separates a whole multi-digits number to separated numbers?

I have a problem in this code.
When i run it, and after that i insert a two digits number, the script separates it. Ex.: enter 12 shows 1 even and 1 odd; enter 26 shows 2 even;
I want it to be mixed, so if i enter a two digits number or more (ex.432152) that needs to be 1 sum, 1 value, and show as 1 even number. Thank you for the opportunity to ask for help here!
function countfromzero() {
if (document.getElementById("maintextbox").value !="") {
CalculateNumbers();
}
}
function CalculateNumbers() {
var arr = [];
var asd = 0;
var evn = 0;
arr = document.getElementById("maintextbox").value;
arr = arr.replace(/, | /g, "");
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
asd++;
}
else {
evn++;
}
}
document.getElementById("eventextbox").value = evn;
document.getElementById("oddtextbox").value = asd;
}
<input type="text" name="maintextbox" id="maintextbox">
<input type="button" id="buttton" name="Process" value="Process" onclick="countfromzero();"><br>
Even:<input type="text" name="eventextbox" id="eventextbox"><br>
Odd:<input type="text" name="oddtextbox" id="oddtextbox">
Your arr variable is not an array as you apparently wanted it to be.
Change the replace method to a split method (with a slightly different RegEx) and you are done
function countfromzero() {
if (document.getElementById("maintextbox").value !="") {
CalculateNumbers();
}
}
function CalculateNumbers() {
var arr = [];
var asd = 0;
var evn = 0;
var str = document.getElementById("maintextbox").value;
arr = str.split(/[^\d]+/g);
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
asd++;
}
else {
evn++;
}
}
document.getElementById("eventextbox").value = evn;
document.getElementById("oddtextbox").value = asd;
}
<input type="text" name="maintextbox" id="maintextbox" value="432152">
<input type="button" id="buttton" name="Process" value="Process" onclick="countfromzero();"><br>
Even:<input type="text" name="eventextbox" id="eventextbox"><br>
Odd:<input type="text" name="oddtextbox" id="oddtextbox">
Consider HerrSerker's Answer since it's optimized to allow sequences of numbers, while mine doesn't
You treated your number as an array, and your for-loop iterated through each digit in your number to check if it's even or odd.
You just have to get rid of the loop, and change your "arr" to not be an array anymore.
function countfromzero() {
if (document.getElementById("maintextbox").value != "") {
CalculateNumbers();
}
}
function CalculateNumbers() {
var arr;
var asd = 0;
var evn = 0;
arr = document.getElementById("maintextbox").value;
arr = arr.replace(/, | /g, "");
if (arr % 2 != 0) {
asd++;
} else {
evn++;
}
document.getElementById("eventextbox").value = evn;
document.getElementById("oddtextbox").value = asd;
}
<input type="text" name="maintextbox" id="maintextbox">
<input type="button" id="buttton" name="Process" value="Process" onclick="countfromzero();"> Even:
<input type="text" name="eventextbox" id="eventextbox"> Odd:
<input type="text" name="oddtextbox" id="oddtextbox">

Increment numbers at end of alphanumeric string in JavaScript

I have alphanumeric strings that will always end in a number, but which may have other numbers embedded early on.
I need to increment the numeric ending and return new ID numbers.
Example:
A48-DBD7-398
Which will be incremented in a loop:
A48-DBD7-398
A48-DBD7-399
A48-DBD7-400
How do I separate out the numeric tail from the rest of the string, and then save the two parts into different variables?
I found several other S.O. questions that split numbers out of a string, but they cannot handle mixed alphanumeric characters in the first part -- or else they split out ALL the numbers, regardless where they are. I need to get only the trailing digits.
Update
I found a case where my solution does not work:
ABC123-DE45-1
Duplicates as:
ABC2
ABC3
ABC4
JS Fiddle demo
If you are interested in a different approach you could do something like this:
$('button').click(function () {
var value = $('#in').val(); // get value
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function (match, n) {
return ++n; // parse to int and increment number
}); // replace using pattern
$('#result')[0].innerHTML += '<br>' + value;
}
});
My 2 cents: use regex to identify the pattern and increment the last part.
function incrementAlphanumeric(str) {
const numPart = str.match(/(0?[1-9])+$|0?([1-9]+?0+)$/)[0];
const strPart = str.slice(0, str.indexOf(numPart));
const isLastIndexNine = numPart.match(/9$/);
// If we have a leading zero (e.g. - 'L100A099')
// or there is no prefix - we should just increment the number
if (isLastIndexNine || strPart != null) {
return strPart + numPart.replace(/\d+$/, (n) => ++n );
}
// Increment the number and add the missing zero
else {
return strPart + '0' + numPart.replace(/\d+$/, (n) => ++n );
}
}
works with the following formats for example:
TEST01A06
TEST-100-A100
TEST0001B-101
TEST001A100
TEST001A91
TEST1101
TEST1010
1010
Demo Repl - https://repl.it/#EdoMagen/Increment-alphanumeric-string
Here is another solution, in case it helps
$('button').click(function() {
var ser = $('#in').val();
var arr = ser.split("-");
var num = parseInt(arr[arr.length - 1]);
arr.splice(-1, 1);
var str = arr.join ('-');
for (n = 1; n <= 5; n++) {
num++;
ser = str + '-' + num;
$('#result').html($('#result').html() + '<br>' + ser);
}
});
div{width:80%;margin-top:30px;background:wheat;}
<input id="in" type="text" value="ABC123-DE45-1" />
<button>Go</button>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I figured it out, and am posting the question for future seekers.
JS Fiddle demo
HTML:
<input id="in" type="text" value="A48-DBD7-395" />
<button>Go</button>
<div id="result"></div>
js/jQ:
$('button').click(function(){
var ser = $('#in').val();
var num = parseInt(ser.match(/\d+$/));
var pos = ser.indexOf(num);
var str = ser.slice(0,pos);
for (n=1;n<=5;n++){
num++;
ser = str + num;
$('#result').html( $('#result').html() +'<br>'+ser);
}
});
const s = "A48-DBD7-398";
s.split('-').reduce((a,b)=>{
if(Number(b)){b = Number(b) + 1}
return a +'-'+ b;
})
> "A48-DBD7-399"

Looping Through an Array of Characters

I would like to loop an array for a specific set of characters that is constantly changing. From there on I want to toggle case the letters, and I've been told to use this specific code but I can't get it to work. The code MUST loop through an array of characters, where the characters are coming from an "input" textbox. How can I fix this?
I should mention that I'm doing this for class in high school, so I'm no where near perfect at coding.
<html>
<head>
<script type="text/javascript">
function toggleCase() {
var i = document.getElementById("input").value.length;
var word = document.getElementById("input").value;
var chop =new array(i);
for (a=i; a <= i; a++) {
character[i] = word.slice(i-1,i)
if (character[i] == character[i].toUpperCase;){
character[i] = character[i].toLowerCase();
}
else {
character[i] = character[i].toUpperCase();
}
}
var final
for (a=i; a <= i; a++) {
final += character[i];
}
document.getElementById("output").value = final
}
</script>
</head>
<body>
<p>Enter letters for conversion:</p>
<form>
<input type="text" name="input" id="input" value="sample" maxlength="10"><br />
<input type="text" name="output" id="output" value="" /> <br/>
<input type="checkbox" name="toggle" value="ToggleCase" onClick="toggleCase(this.form)">Toggle Case<br/>
</form>
</body>
</html>
Maybe you should take a look at some api's and howtos but here is your code:
<html>
<head>
<script type="text/javascript">
function toggleCase() {
var text = document.getElementById("input").value;
var character = new Array(text.length);
for (i=0, a = text.length; i < a; i++) {
character[i] = text[i];
if (character[i] == character[i].toUpperCase){
character[i] = character[i].toLowerCase();
}
else {
character[i] = character[i].toUpperCase();
}
}
document.getElementById("output").value = character.join('');
}
</script>
</head>
<body>
<p>Enter letters for conversion:</p>
<form>
<input type="text" name="input" id="input" value="sample" maxlength="10"><br />
<input type="text" name="output" id="output" value="" /> <br/>
<input type="checkbox" name="toggle" value="ToggleCase" onClick="toggleCase()">Toggle Case<br/>
</form>
</body>
</html>
function toggleCase() {
var str = document.getElementById("input").value;
for (var i=0; i<str.length; i++) {
str[i] = (str[i]==str[i].toUpperCase() ? str[i].toLowerCase() : str[i].toUpperCase());
}
document.getElementById("output").value = str;
}
that's a for loop that does the job. and remember .toUpperCase and .toLowerCase are functions
You might want to take a look at the String's split method.
var str = 'foo bar baz';
The simplest way to convert a string into a char array is by passing an empty string into the split method.
var charArray = str.split(''):
// charArray === ['f','o','o' ... 'b','a','z'];
Also a FYI, passing a space character into split will give you an array of words.
var wordArray = str.split(' ');
// wordArray === ['foo', 'bar', 'baz'];
I'm a little unclear what you have to solve but it looks like you want a function convert upper case letter into lowercase letters and vise versa.
var userInput = document.getElementById('someTextBox');
// If you want to be fancy you could use JQuery
// var userInput = $(#someTextBox').value()
function toggledCase( str ) {
var characters = str.split('');
// The split method still uses iteration so should be able to say it
// satisfies the argument of looping through each character.
// Split just provides a good abstraction to interface with.
var toggledCharacters = [];
var i;
var ch;
for( i in characters ) {
// For in loops on strings will return the indexes instead
// of the characters
ch = characters[i];
if( ch.toUpperCase() === ch ){
toggledCharacters.push( ch.toLowerCase() );
} else {
toggledCharacters.push( ch.toUpperCase() );
}
// If you like one-liners,
// the conditional if statement could be replace with a ternay statement.
// toggledCharacters.push( ( ch.toUpperCase() === ch ) ?
// ch.toLowerCase() : ch.toUpperCase();
}
return toggledCharacters;
}
My toggledCharacters method only returns an array of characters, so if you want back as a string you could make a for loop;
var arr = toggledCharacters('Foo'); // str = 'fOO';
var str = '';
var i, ch;
for ( i in arr ) {
str += arr[i]; // += is just a short hand notation of saying
// str = str + arr[i];
}
If you are lazy and like one-liners, take a look at functional programming. It's kinda out of scope since you are still in High School.
var arr = toggledCharacters('Foo'); // str = 'fOO';
var str = arr.reduce( function(str, ch) {
return str + ch;
} );
Anyway, this looks a lot cleaner to me than what the teacher outlined.
function toggledCharacters(input) {
input = input.split('');
var output = [];
var i, ch;
for( i in input ) {
output.push( ( input[i].toUpper() === input[i] ) ?
input[i].toLower() : input[i].toUpper()
);
}
return output.reduce(
function(str, ch) {
return str + ch;
}
);
}
Edit:
Oh, I just notice that nowhere in that code the is the check's box boolean value being evaluated.
var checkBox = document.getElementByName('toggle');
var inputTextBox = document.getElementById('input');
var outputTextBox = document.getElementById('output');
var result = inputTextBox.value;
if( checkBox.checked ) {
result = toggleCase( result );
}
outputTextBox.value = result;
Oh another FYI since you are a beginner. Make sure you know to use the browser's console.
If you are on Firefox, grab the firebug app.
Chrome, press Ctrl-Shift-C.
IE has one as well, I just don't care to ever use it.
The console makes it easier to experiment with JS then compared to making html demo page and assuming the code is working as it should.
Plus, these developer tools can show you underlying methods of an object. It makes for a great and quick way to learn JS.

What's the best way to count keywords in JavaScript?

What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that.
Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.
Cut, paste + execute demo:
var text = "Text to be examined to determine which n words are used the most";
// Find 'em!
var wordRegExp = /\w+(?:'\w{1,2})?/g;
var words = {};
var matches;
while ((matches = wordRegExp.exec(text)) != null)
{
var word = matches[0].toLowerCase();
if (typeof words[word] == "undefined")
{
words[word] = 1;
}
else
{
words[word]++;
}
}
// Sort 'em!
var wordList = [];
for (var word in words)
{
if (words.hasOwnProperty(word))
{
wordList.push([word, words[word]]);
}
}
wordList.sort(function(a, b) { return b[1] - a[1]; });
// Come back any time, straaanger!
var n = 10;
var message = ["The top " + n + " words are:"];
for (var i = 0; i < n; i++)
{
message.push(wordList[i][0] + " - " + wordList[i][1] + " occurance" +
(wordList[i][1] == 1 ? "" : "s"));
}
alert(message.join("\n"));
Reusable function:
function getTopNWords(text, n)
{
var wordRegExp = /\w+(?:'\w{1,2})?/g;
var words = {};
var matches;
while ((matches = wordRegExp.exec(text)) != null)
{
var word = matches[0].toLowerCase();
if (typeof words[word] == "undefined")
{
words[word] = 1;
}
else
{
words[word]++;
}
}
var wordList = [];
for (var word in words)
{
if (words.hasOwnProperty(word))
{
wordList.push([word, words[word]]);
}
}
wordList.sort(function(a, b) { return b[1] - a[1]; });
var topWords = [];
for (var i = 0; i < n; i++)
{
topWords.push(wordList[i][0]);
}
return topWords;
}
Once you have that array of words cleaned up, and let's say you call it wordArray:
var keywordRegistry = {};
for(var i = 0; i < wordArray.length; i++) {
if(keywordRegistry.hasOwnProperty(wordArray[i]) == false) {
keywordRegistry[wordArray[i]] = 0;
}
keywordRegistry[wordArray[i]] = keywordRegistry[wordArray[i]] + 1;
}
// now keywordRegistry will have, as properties, all of the
// words in your word array with their respective counts
// this will alert (choose something better than alert) all words and their counts
for(var keyword in keywordRegistry) {
alert("The keyword '" + keyword + "' occurred " + keywordRegistry[keyword] + " times");
}
That should give you the basics of doing this part of the work.
Try to split you string on words and count the resulting words, then sort on the counts.
This builds upon a previous answer by insin by only having one loop:
function top_words(text, n) {
// Split text on non word characters
var words = text.toLowerCase().split(/\W+/)
var positions = new Array()
var word_counts = new Array()
for (var i=0; i<words.length; i++) {
var word = words[i]
if (!word) {
continue
}
if (typeof positions[word] == 'undefined') {
positions[word] = word_counts.length
word_counts.push([word, 1])
} else {
word_counts[positions[word]][1]++
}
}
// Put most frequent words at the beginning.
word_counts.sort(function (a, b) {return b[1] - a[1]})
// Return the first n items
return word_counts.slice(0, n)
}
// Let's see if it works.
var text = "Words in here are repeated. Are repeated, repeated!"
alert(top_words(text, 3))
The result of the example is: [['repeated',3], ['are',2], ['words', 1]]
I would do exactly what you have mentioned above to isolate each word. I would then probably add each word as the index of an array with the number of occurrences as the value.
For example:
var a = new Array;
a[word] = a[word]?a[word]+1:1;
Now you know how many unique words there are (a.length) and how many occurrences of each word existed (a[word]).

Categories

Resources