Measuring the number of distinct words within a given set of strings

Describing my attempt to create a function that processes string arrays by adding unique words to a word array, and incrementing the count of existing words in the count array:

var words = [];
var counts = [];

calculate([a, b]);
calculate([a, c]);

function calculate(result) {
    for (var i = 0; i < result.length; i++) {
        var check = 0;
        for (var j = 0; i < tags.length; i++) {
            if (result[i] == tags[j]) {
                check = 1;
                counts[i] = counts[i] + 20;
            }
        }
        if (check == 0) {
            tags.push(result[i]);
            counts.push(20);
        }
        check = 0;
    }
}

However, the actual output is:

words = a, b count = 2, 1

When I was expecting:

words = a, b, c count = 2, 1, 1

Your help is greatly appreciated!

Answer №1

Dividing the issue into smaller methods with descriptive names can assist in solving the problem logically.

Give this a try:

<script type="text/javascript">
var words = [];
var counts = [];
calculate(["x", "y"]);
calculate(["x", "z"]);
console.log(words);
console.log(counts);

function calculate(result) {
    for (var i=0; i<result.length; i++) {
        if (array_contains(words, result[i])) {
            counts[result[i]]++;
        } else {
            words.push(result[i]);
            counts[result[i]] = 1;
        }
    }
}

function array_contains(array, value) {
    for (var i=0; i<array.length; i++)
        if (array[i] == value)
            return true;
    return false;
}

</script>

Result:

["x", "y", "z"]
[]
x 2
y 1
z 1

Answer №2

Kindly review the following snippet: you are able to examine it at: http://jsfiddle.net/knqz6ftw/

var words = [];
var counts = [];

calculate(['a', 'b']);
calculate(['a', 'c']);
calculate(['a', 'b', 'c']);

function calculate(inputs) {
    for (var i = 0; i < inputs.length; i++) {
    var isExist = false;
    for (var j = 0; j < words.length; j++) {
        if (inputs[i] == words[j]) {
            isExist = true
            counts[i] = counts[i] + 1;
        }
    }
    if (!isExist) {
        words.push(inputs[i]);
        counts.push(1);
    }
    isExist = false;
}
}

console.log(words);
console.log(counts);

Result shown below:

["a", "b", "c"] (index):46
[3, 2, 2] 

Answer №3

We had a few issues with the code initially, but here is the corrected version:

var words = [];
var counts = [];

calculate(["apple", "banana"]);
calculate(["apple", "cherry"]);

function calculate(result) {
    for (var i = 0; i < result.length; i++) {
        var check = 0;
        for (var j = 0; j < words.length; j++) {
            if (result[i] == words[j]) {
                check = 1;
                ++counts[j];
            }
        }
        if (check == 0) {
            words.push(result[i]);
            counts.push(1);
        }
        check = 0;
    }
}

JSBin Link: http://jsbin.com/hawaco/2/edit?js,console

Changes made:

  • Replaced array literals with string values: ["apple","banana"] and ["apple","cherry"]
  • Updated references from tags to words
  • Adjusted numbers from 20s to 1s
  • Improved clarity in the increment of counts[j]
  • Corrected the use of i and j indices

Considerations for improvement:

  • Possibly convert the arrays into a dictionary for simpler code: {"apple":1, "banana":1}
  • Allow for passing in array names to support different accumulators, or combine method and arrays into an object

Simplified version:

var seen = {};

count(["apple", "banana"], seen);
count(["apple", "cherry"], seen);

function count(words, accumulator) {
    for (var i = 0; i < words.length; ++i) {
        if(!accumulator.hasOwnProperty(words[i])) {
          accumulator[words[i]] = 1;
        } else {
          ++accumulator[words[i]];
        }
    }
}

Result:

>> seen
[object Object] {
  apple: 2,
  banana: 1,
  cherry: 1
}

JSBin Link: http://jsbin.com/halak/1/edit?js,console

Answer №4

Below is a snippet demonstrating my approach utilizing an object:

  const checkWord = (str) => {
    let collection = {};
    // break down the string into individual words
    let words = str.split(' ');
    words.forEach((word) => {
     collection[word] = word;
   });
   // iterate through the words to compare and keep track of their occurrences
   for (let j = 0; j < words.length; j++) {
     if (words[j] === collection[words[j]]) {
       collection[words[j]] = 0;
     }
     collection[words[j]]++
   }
   console.log(collection);
 };

An alternative way to implement this is by utilizing the reduce method:

  const checkWord = (str) => {
  let collection = {};
  let words = str.split(' ');
  words.forEach((word) => {
     collection[word] = word;
   });
  for (var i = 0; i < words.length; i++) {
    if (words[i] === collection[words[i]]) {
      collection[words[i]] = 0;
    }
  }
  let total = words.reduce((occurrences, word) => {
    collection[word]++
    return collection;
}, 0);
    console.log(total);
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create a single code that can be used for various buttons that perform the same function?

Whenever I click the right button, the left button appears and when I reach the last page, the right button disappears. However, this behavior is affecting both sections. Is there a way to write separate code for each section? I managed to make it work by ...

How to efficiently transfer dynamically generated table row data to JavaScript for database submission using the POST method

Currently, I am working with Laravel and facing an issue related to dynamic rows in my form. Each row has its own form with unique values. My goal is to pass the form data along with values to JavaScript when the submit button is clicked without refreshin ...

Is it possible to retrieve local variable JSON arrays using ajax/getJson()?

When starting a project without a database or data source, I often create json arrays in a *.js file to populate screens until the data modeling or database creation is complete. I am trying to figure out how to write an ajax/getJson() function to access ...

What steps are involved in generating a scene dynamically with A-Frame?

Looking to transition from declarative coding in js and html to a programmatic approach with Aframe? You might be wondering if it's possible to modify your scene dynamically, here is an example of what you're trying to achieve: <!DOCTYPE html ...

Steps for assigning an id to an element using Selenium

When using Selenium, you have the ability to access the underlying DOM of the browser being manipulated through IWebElement instances. For example: IWebElement domWrapper = driver.FindElement(By.Name("q")); But what if you have the "domWrapper" instance ...

Removing characters that are not numbers

I have a string array structured like this: arr[0] = "AB82374892"; arr[1] = "QBA9980309"; arr[2] = "AC00098320"; and so forth. How can I remove all non-numeric characters from each array element? Resulting in the updated array: arr[0] ...

Send a parameter to an Angular directive when clicked

I am working on a directive that will allow me to retrieve parameters upon clicking. I need to access the child data within the click event to determine if it has children or not. ..... html div ng-app="treeApp"> <ul> <treeparent>< ...

State in Vuex is failing to update effectively when actions are being utilized

I'm trying to wrap my head around VueX, but I'm having trouble getting Axios to work with it. In my store.js file, I have the following setup: state: { cards: [], currentPage: 1, lastPage: 2, }, actions: { loadGradients(page ...

What is the best way to loop through a group of WebElements, and only log the results that contain a specific substring?

In my test case, I'm utilizing Mocha to handle the scenario. The test appears to be passing successfully, however, no logs are being printed... it('Is 'Mooooooo!!!! I2MaC0W' a Substring in Results?', function() { this.timeout(50 ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

Retrieving Google Maps Geocoding JSON through an Express API

Recently, I have been teaching myself about Node.js and Express, specifically focusing on returning JSON results from a Google Maps Geocoding API request. I have managed to make it work using the `require` module, but I am determined to understand where I ...

JavaScript regex problem

As I am handling a specific string: £1,134.00 (£1,360.80 inc VAT) I am currently attempting to isolate the numerical values as follows: ['1,134.00','1,360.80'] My approach involves utilizing this regex pattern in Javascript: /&bs ...

Combining PHP multidimensional arrays

I am looking for assistance on how to achieve the following structure: [pad] => Array ( [padi] => Array ( [Date] => 2016-01-01 [Val] => 1 [Premium] => 100 ) ...

The functionality of Angular-ui-router becomes compromised when run through gulp for minification

I have a simple angular.js application that adheres to the best practices mentioned here. angular .module('myApp', ['ui.router']); (function() { function configureRoutes($stateProvider, $urlRouterProvider) { $urlRouterPr ...

Sending information from tinyMCE text field to PHP using AJAXgetMethod

When I use a TinyMCE 4.0 text field to post HTML data through AJAX, I am encountering an issue where the data doesn't reach the server side properly. In Firefox Firebug, it shows that I have posted this data: attendanceID=&noteID=&Category=2 ...

What is the best way to extract the date January 1, 1970 from a datepicker?

Currently, I am utilizing a datepicker along with a function that converts dates from dd-mm-yyyy to yyyy-mm-dd format. The dates in the database are stored in yyyy-mm-dd format, so I need to first convert them to dd-mm-yyyy for better readability. When sub ...

The coordinates of the event do not match the coordinates of the location. Successful AJAX response data

How can I retrieve the accurate latitude and longitude when the Google Maps marker finishes dragging? It's confusing because for the same exact point, two different (but very approximate) coordinates are provided. Here are some example results for t ...

Steps to remove a scrollbar from a fullscreen slider

Can anyone provide code examples on how to disable the scroll bar on a full screen slider? I want to have a scroll down button on each slider that, when clicked, will show the scrollbar only below the slider. I don't want the scrollbar to be visible ...

Check if the provided user email is already in use using the express validator

I have configured the following route in my Node.js API application: const { body } = require("express-validator"); router.post( "/user/signup", [ body("firstName").not().isEmpty().withMessage("First name is required"), body("lastName").not().i ...

incorrect encoding of Greek characters due to the multer upload package

When uploading files with Greek characters, the uploaded titles are saved as ΠÏξ Îαξ & ÎαÏÏιμιÏαίοι Here is the code for multer variables inside a js file: const storage = multer.diskStorage({ destination: f ...