Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response.

There are 3 tasks I need to accomplish here:-

  1. Calculate the word count in the document.
  2. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech.

API :- https://dictionary.yandex.net/api/v1/dicservice.json/lookup Key :- something..

  1. Display the results of the top 3 words list in JSON format

All operations should be done asynchronously.

const fetch = require("node-fetch");

async function fetchTest() {
    let response = await

    fetch('http://norvig.com/big.txt')
        .then(response => response.text())
        .then((response) => {
            console.log(response)
        })
        .catch(err => console.log(err));

}

(async() => {
    await fetchTest();
})();

EDIT:-

const fetch = require("node-fetch");

async function fetchTest(responses) {
    let response = await

    fetch('http://norvig.com/big.txt')
        .then(response => response.text())
        .then((response) => {
            console.log(response); // ------------------> read text  from doc

            var words = response.split(/[ \.\?!,\*'"]+/);
            console.log(words);
                
               var array = Object.keys(words).map(function(key) {
                return { text: words[key], size: key };
                });

                console.log(array); //-----------------------> occurence count of words

                   var sortedKeys =  array.sort(function (a, b) {
                    return  b.size - a.size ;
                    });
                    var newarr = sortedKeys.slice(0, 10);
                    console.log(newarr); // --------------> top 10 text and occurence

                    var permittedValues = newarr.map(value => value.text);
                    console.log(permittedValues); //---------------> sorted key in array


                    fetch('https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=domething_&lang=en-en&text=in&callback=myCallback')
                        .then(responses => responses.text())
                        .catch(err => console.error(err));
                        console.log(this.responses);
                                             
                       
         })
        .catch(err => console.log(err));

}

(async() => {
    await fetchTest();
})();

Having trouble with fetching API data in JSON format to display synonyms and parts of speech. Can someone help me figure out where I am making a mistake?

Answer №1

It appears that this question resembles a typical task given as homework. By examining the lookup call's documentation:

You will find that it provides an array of synonyms and identifies the part of speech at no cost, simplifying the process of identifying the most frequently used words.

Although it may not be the most innovative approach, you can efficiently tackle this by utilizing a dictionary. Simply iterate through once to tally the occurrences in a dictionary, then sort the key/value pairs based on frequency to obtain the desired outcome. The top ten words can easily be identified, while the remaining words can be retrieved using the provided API, as demonstrated by your current code showcasing how to make asynchronous calls to the API.

Afterward, proceeding with the solution should be fairly straightforward.

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

What is the best way to incorporate an AppBar featuring a Back to Top button from Material UI for React into my application?

While exploring the Material UI documentation, I came across this interesting code snippet: import React from 'react'; import PropTypes from 'prop-types'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from &ap ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked. However, we are facing issues where clicking on the order button doesn't register in the applicat ...

Using the Rails cocoon gem to populate numerous input fields

I'm currently implementing the cocoon gem in my rails application, where I have a form with two nested fields (categories and subcategories). Initially, only the first field is visible while the second one remains hidden. When the first select field h ...

Receive Real-Time Notifications -> Update Title Using an Array Retrieved from a JSON File

I've been working on updating a live chart every 5 seconds with new data from the database. While I could easily update the information, I encountered a problem when trying to set a path within the chart options for tooltips callbacks afterTitle. Spec ...

Repairing a syntax error in a jQuery selector variable

$(".className").click(function(){ var link = $(this).find("a").attr('href'); //output is '#myID' var findItems = $(link '.mydiv').length; //WRONG var findItems = $(link + '.mydiv').length; ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

Sending a JSONP request to a PHP script

For my application submission, I am trying to send a JSON object to a PHP script that will return a JSON response. The challenge here is that the domain does not comply with the same-origin policy, meaning the JSON is being sent from a different domain. Up ...

JavaScript not properly rendering CSS styles

If I insert the following HTML statically, the CSS style is correctly applied. HTML: <li class="connector"> <a href="#"> <img src="css/images/temp/connector2.png" alt="" width="192" height="192"> <span class="sr-only"& ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Discover the secret to incorporating concealed text in WordPress with a hidden div through the power of JavaScript

For a while now, I've been trying to implement a functionality where clicking on a text reveals a dropdown menu with more information, similar to a "read more" feature. I have limited experience in Java or jQuery, and I can't figure out if the i ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...

Encountering a parsing failure in the _app.js file of a new Next.js project: Unexpected token

When starting a new Next.js project, I use the following command: npx create-next-app After moving into the project folder and running npm run dev, I encounter the following error: C:/Users/mikke/Documents/Projects/next-project/pages/_app.js 4:9 Module pa ...

Is it considered poor form to use res.locals in Node.js with Express?

Is it considered bad practice to use res.locals as shown in this code example? Are there potential issues that could arise from using it in this manner? app.use((req, res, next) => { const session = req.cookies.session if (session) { db. ...

Using the Parallax Effect in React

I'm currently working on implementing a parallax effect in React and I've encountered an error that's giving me trouble: Below is the snippet of JavaScript code I have for the parallax effect: export const parallax = document.getElementsBy ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

Dynamic form validation using jQuery

I am facing a challenge with validating a dynamic form on the user side. My goal is to ensure that if a user fills out one column in a row, they are required to fill out the remaining columns as well. For example, filling out the CC # should prompt the use ...