undefined array counting words: object - javascript
So i am having issues coming up with an undefined array element.
1) cant get my undefined array to work
2) i want it to output the array as an occurrence of the word and number of times.
var wordCount =[];
splitAT.sort();
alert(splitAT);
for (var i = 0; i < splitAT.length; i++)
{
if(splitAT[i] in wordCount)
{
wordCount.push(1);
}
else
{
wordCount[splitAT[i]] = 1;
}
document.write('[' + splitAT[i] + '][' + wordCount[i] + ']<br>')
alert("your next wordcount is");
alert(wordCount); // this is just so i know where i am in the program.
alert("END");
First up, use the right tool for the job: wordCount should be an object rather than an array:
var wordCount = {}; // note, curly brackets
...because you plan to access it using strings as keys, not numeric array indices. (Yes, an array will work for this purpose, but it's not an array's intended purpose.)
Then in your loop, if the current word is already in wordCount you want to add 1 to the existing value, not use .push(1) which will insert a new array element at the end of the numerically indexed elements.
// WRONG:
wordCount.push(1); // inserts a new element
// RIGHT:
wordCount[splitAT[i]]++; // increments the current value
Putting that together, you would count the words like this:
var wordCount = {};
splitAT.sort();
for (var i = 0; i < splitAT.length; i++) {
if(splitAT[i] in wordCount) {
wordCount[splitAT[i]]++;
} else {
wordCount[splitAT[i]] = 1;
}
}
"i want it to output the array as an occurrence of the word and number of times."
To output the results you could do something like this:
var output = [];
for (var k in wordCount)
output.push("'" + k + "' appears " + wordCount[k] + " time(s).");
document.getElementById("NumCount").value = output.join("\n");
(Assuming you want to output to a textarea element with id="NumCount", which is what you had in your fiddle.)
Related
Find matching elements in an array
I have an array like this {A1,B5,C6,A2,B7,C4}; I want to loop through the array and find the matching element and then do some manipulation in that match. The match in the above array is A1 and A2, B5 and B7 and finally C6 and C4. Below is what I have done so far: var arr = {A1,B5,C6,A2,B7,C4}; for (i=0; i < arr.length/2; i++) // Only running till length/2 since there is always another match hence don't need to run through all the length probably { for (j=i+1; j < arr.length; j++) { if(arr[i].charAt(0) == arr[j].charAt(0)) { j=arr.length; //This is done to end the inner loop Do something; //if the matching element is found, ideally the i loop should ignore this record. I don't know how to do this. } } }
You will need to sort the array first to make it easier to find the matching pairs. Here is one way you can modify your code. var arr = ['A1','B5','C6','A2','B7','C4'] arr.sort(); console.log("Sorted array : " + arr); for (i=0; i < arr.length -1; i++) // Only running till length/2 since there is always another match hence don't need to run through all the length probably { if(arr[i].charAt(0) == arr[i+1].charAt(0)) { j=arr.length; //This is done to end the inner loop console.log("Match found : " + arr[i].charAt(0)); //if the matching element is found, ideally the i loop should ignore this record. I don't know how to do this. } }
You could create an object with all the matches, like so: var arr = ['A1','B5','C6','A2','B7','C4']; var setsOfMatches = {}; arr.forEach(function(currentItem) { var firstLetter = [currentItem.charAt(0)]; if (setsOfMatches[firstLetter]) { //If we have a set for this letter already setsOfMatches[firstLetter].push(currentItem); //Add this item to it } else { setsOfMatches[firstLetter] = [currentItem]; //Create the set } }); //console.log(setsOfMatches); //{ // A:["A1","A2"], // B:["B5","B7"], // C:["C6","C4"] //} //Iterate through the sets of matches for (var set in setsOfMatches) { console.log("Set " + set + ": " + setsOfMatches[set]); }
Get duplicate character in javascript
How to get duplicate character in JavaScript, As like input: aaabcccdeffa Output: a4bc3def2
Try this: var str = "aaabcccdeffa"; // Original string // We are going to create a key-value array to store the number of occurance // per letter (eg. 'a' : 4, 'b' : 1 etc.) var store = {}; // Next we loop through each letter in the string for (var a in str) { if (store[str[a]] == undefined) { // If this letter has not ben found before, we set the count to 1 (first occurance) store[str[a]] = 1; } else { // else if the letter has been found, we increase the count by one store[str[a]] += 1; } } // At this point, we have a key value array that contains the count of each letter // Next, we loop through this array to generate the new string var newStr = ''; // Initialise new string for (var char in store) { newStr += char; // append the letter to the string if (store[char] > 1) { newStr += store[char]; // If the count is more than one, we want to show the number too, so we append the number to the string } } Output will be in newStr
you can use a HashTable, which in javascript is done through an Object. This code works function duplicateCharacters(str) { //Create an empty object var hashTable = {}; for(var i = 0; i < str.length; i++){ //Check if the character has already been registered //If false, register it and link a 1 to it //If true, increment the integer linked to it if (hashTable.hasOwnProperty(str[i])) hashTable[str[i].toString()]++; else hashTable[str[i].toString()] = 1; } var output = ""; //Go through the hashTable for(var key in hashTable) { //Concatenate the key output += key.toString(); //If the character only appeared once, do not add it if(hashTable[key] != 1) output += hashTable[key].toString() } return output; }
Here is the reference code which uses both jquery and Regular expression for calculating the frequency of the character. // Variable Declaration with Source text var sourceText="aaabcccdeffa"; var resultText=""; // Splitting the source text to array var sourceTextArray=sourceText.split(""); var uniqueText = []; //Fetches Unique text from sourceTextArray in order $.each(sourceTextArray, function(i, el){ if($.inArray(el, uniqueText) === -1) uniqueText.push(el); }); //Iteration with unique text array $.each(uniqueText, function(i, el){ //Regular Expression approach to calculate frequency of character with source text resultText+=(sourceText.match(new RegExp(el, "g")) || []).length>1?el+(sourceText.match(new RegExp(el, "g")) || []).length:el; }); alert(resultText); Working Example Here
Pull information from a data file?
I have over 170000 entries of data in data file in this format: 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;: 1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;: Now each data array starts with a unique id and i was wondering is there a convenient way to push each entry 1479661 then 1479662 every second to an array and assign the values within the unique id into 6 fields that update. Now I ask if there is a more convenient way as currently I am using this method: Data comprises of three chunks in a single line Split the link into chunks var chunkOne = [1479661]; var chunkTwo = [-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00]; var chunkThree = [117,-1397,7,7.00,"A","Dead"]; Then get length of each array: var chunkOneLength = chunkOne.length; var chunkTwoLength = chunkTwo.length; var chunkThreeLength = chunkThree.length; Pick out the nth value in the array depending on the data chunk: //uniqueID set as first for (var i = 0; i < chunkOneLength; i = i + 1) { // useful code would go here alert("This is the unique ID " + chunkOne[i]); } //teamval for (var i = 0; i < chunkTwoLength; i = i + 6) { // useful code would go here alert("This is the teamVal " + chunkTwo[i]); } Now the only problem I see with this method, is that the original data array will need to be formatted and separated into chunks every time.
As you have a separator on each section i.e. : you can actually use split to split them up like below and push them into a array and only have to do 2 loops - firstly pushing the split data in a new array and then looping through them and populating the structure. Please note as long as each chunk of data is separated with : this will work with anything even if you expand the data later. obviously it will not work if you remove the : separator. example below: var splitChucks = []; var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"]; for (var i = 0; i < chucks.length; i++){ splitChucks.push(chucks[i].split(':')) } for (var h = 0; h < splitChucks.length; h++) { alert("This is the unique ID " + splitChucks[h][0]); alert("This is the teamVal " + splitChucks[h][1]); } Hope this helps, this is a much more efficient way to do your task :)
var splitChucks = []; var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"]; for (var i = 0; i < chucks.length; i++){ splitChucks.push(chucks[i].split(':')) } for (var h = 0; h < splitChucks.length; h++) { alert("This is the unique ID " + splitChucks[h][0]); alert("This is the teamVal " + splitChucks[h][1]); }
One of the best purposes of an unique ID is to act as an index. So, instead of iterating over your index array (chunkOne), use ID as an Object key! // 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;: var data = { 1479661: [ -1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00,117,-1397,7,7.00,"A","Dead" ] // More data... }; Object.keys(data).forEach(function(key) { console.log('This is ID ' + key); data[key].forEach(function(value,index,array) { console.log('Index ' + index + ' of data key ' + key + ':'); console.log(data[key][index]); }); }); Test this on any modern browser's console or node.js instance to see results.
Accessing indexes of a string inside an array and taking the sum
Ok so I am trying to access each individual number in the strings inside of this array. var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245']; var str = ""; for (i=0; i<array.length; i++) { str = array[i]; } The problem is that this is the output: '999-992-1313' and not the first element array[0]: '818-625-9945' When I try doing a nested for loop to go through each element inside the string I am having trouble stating those elements. var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245']; for (i=0; i<array.length; i++) { for (j=0; j<array[i].length; j++) { console.log(array[i][j]); } } I do not know how to access each individual number inside of the string array[i]. I would like to find a way to make a counter such that if I encounter the number '8' I add 8 to the total score, so I can take the sum of each individual string element and see which number has the highest sum. var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245']; for (i=0; i<array.length; i++) { for (j=0; j<array[i].length; j++) { if (array[i](j).indexOf('8') !== -1) { // add one to total score // then find a way to increase the index to the next index (might need help here also please) } } }
Mabe this works for you. It utilized Array.prototype.reduce(), Array.prototype.map() and String.prototype.split(). This proposal literates through the given array and splits every string and then filter the gotten array with a check for '8'. The returned array is taken as count and added to the return value from the former iteration of reduce - and returned. var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'], score = array.reduce(function (r, a) { return r + a.split('').filter(function (b) { return b === '8'; }).length; }, 0); document.write('Score: ' + score); A suggested approach with counting all '8' on every string: var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'], score = array.map(function (a) { return a.split('').filter(function (b) { return b === '8'; }).length; }); document.write('Score: ' + score);
Actually rereading your question gave me a better idea of what you want. You simply want to count and retrieve the number of 8's per string and which index in your array conforms with this maximum 8 value. This function retrieves the index where the value was found in the array, how many times 8 was found and what is the string value for this result. (or returns an empty object in case you give in an empty array) This you could easily do with: 'use strict'; var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245']; function getHighestEightCountFromArray(arr) { var max = 0, result = {}; if (arr && arr.forEach) { arr.forEach(function(value, idx) { var cnt = value.split('8').length; if (max < cnt) { // found more nr 8 in this section (nl: cnt - 1) max = cnt; // store the value that gave this max result = { count: cnt - 1, value: value, index: idx }; } }); } return result; } console.log(getHighestEightCountFromArray(array)); The only thing here is that when an equal amount of counts is found, it will still use the first one found, here you could decide which "maximum" should be preferred(first one in the array, or the newest / latest one in the array) OLD I'm not sure which sums you are missing, but you could do it in the following way. There I first loop over all the items in the array, then I use the String.prototype.split function to split the single array items into an array which would then contain ['818', '625', '9945']. Then for each value you can repeat the same style, nl: Split the value you are receiving and then loop over all single values. Those then get convert to a number by using Number.parseInt an then all the values are counted together. There are definitelly shorter ways, but this is a way how you could do it 'use strict'; var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'], sumPerIndex = [], totalSum = 0; array.forEach(function(item, idx) { var values = item.split('-'), subArray = [], itemSum = 0; values.forEach(function(value) { var singleItems = value.split(''), charSum = 0; singleItems.forEach(function(char) { charSum += parseInt(char); }); itemSum += charSum; subArray.push(charSum); console.log('Sum for chars of ' + value + ' = ' + charSum); }); sumPerIndex.push(subArray); totalSum += itemSum; console.log('Sum for single values of ' + item + ' = ' + itemSum); }); console.log('Total sum of all elements: ' + totalSum); console.log('All invidual sums', sumPerIndex);
Using search method from string
I'm trying to count the number of times certain words appear in the strings. Every time I run it I get a uncaught TypeErro: undefined is not a function I just actually need to count the number of times each "major" appears. Below is my code: for(var i = 0; i < sortedarray.length; i++) { if(sortedarray.search("Multimedia") === true) { multimedia += 1; } } console.log(multimedia); Here is my csv file which is stored in a 1d array. "NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS" "Smith, John A","Computer Science","Senior","E" "Johnson, Brenda B","Computer Science","Senior","E" "Green, Daisy L","Information Technology","Senior","E" "Wilson, Don A","Information Technology","Junior","W" "Brown, Jack J","Multimedia","Senior","E" "Schultz, Doug A","Network Administration","Junior","E" "Webber, Justin","Business Administration","Senior","E" "Alexander, Debbie B","Multimedia","Senior","E" "St. John, Susan G","Information Technology","Junior","D" "Finklestein, Harold W","Multimedia","Freshman","E"
You need to search inside each string not the array. To only search inside the "Major" column, you can start your loop at index 1 and increment by 4 : var multimedia = 0; for(var i = 1; i < sortedarray.length; i += 4) { if(sortedarray[i].indexOf("Multimedia") > -1) { multimedia += 1; } } console.log(multimedia);
What you're probably trying to do is: for(var i = 0; i < sortedarray.length; i++) { if(sortedarray[i].indexOf("Multimedia") !== -1) { multimedia++; } } console.log(multimedia); I use indexOf since search is a bit of overkill if you're not using regexes. Also, I replaced the += 1 with ++. It's practically the same.
Here's a more straightforward solution. First you count all the words using reduce, then you can access them with dot notation (or bracket notation if you have a string or dynamic value): var words = ["NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"...] var count = function(xs) { return xs.reduce(function(acc, x) { // If a word already appeared, increment count by one // otherwise initialize count to one acc[x] = ++acc[x] || 1 return acc },{}) // an object to accumulate the results } var counted = count(words) // dot notation counted.Multimedia //=> 3 // bracket notation counted['Information Technology'] //=> 3
I don't know exactly that you need this or not. But I think its better to count each word occurrences in single loop like this: var occurencesOfWords = {}; for(var i = 0; i < sortedarray.length; i++) { var noOfOccurences = (occurencesOfWords[sortedarray[i]]==undefined? 1 : ++occurencesOfWords[sortedarray[i]]); occurencesOfWords[sortedarray[i]] = noOfOccurences; } console.log(JSON.stringify(occurencesOfWords)); So you'll get something like this in the end: {"Multimedia":3,"XYZ":2}
.search is undefined and isn't a function on the array. But exists on the current string you want to check ! Just select the current string in the array with sortedarray[i]. Fix your code like that: for(var i = 0; i < sortedarray.length; i++) { if(sortedarray[i].search("Multimedia") === true) { multimedia += 1; } } console.log(multimedia);