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

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

Sending a series of filtered GET requests to my Express backend in a MERN (MongoDB, Express, React,

I have developed a MERN web application and am in the process of adding some GET methods to retrieve the same item for different scenarios. However, when I attempt to implement a second filter method and pass an existing parameter in my item schema, Postma ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

The request body for MERN full stack development is returning empty

I am currently facing an issue while trying to establish a connection between my client and the backend. Here is the snippet of code I am using: //client const body = { email: value, }; axios.get("http://localhost:5000/checkEmail", body) // ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

Issue: The function "generateActiveToken" is not recognized as a function

I encountered an issue in my Node.js project and I'm unsure about the root cause of this error. Within the config folder, there is a file named generateToken.js which contains the following code snippet: const jwt = require('jsonwebtoken'); ...

Using jQuery UI to dynamically add a widget based on a specific class, rather than relying on

Exploring the world of Apache Cordova and jQueryUI is a new adventure for me. I am currently experimenting with formatting the layout of my index.html using jQueryUI. As mentioned in this section of the jQueryUI tutorial, a widget can be added using the f ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

The React application functions smoothly when executed using react-scripts start, but encounters an "Unexpected SyntaxError: Unexpected Token: <" error upon building

My goal is to deploy my portfolio site using an express server and react-scripts build. Everything works perfectly fine when I run react-scripts start. However, when I try to serve up the build index.js, I encounter the following errors: 2.8b4a0c83.chunk.j ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Excess space at the bottom of the Heatmap chart in Highcharts

I am facing an issue with a heatmap having extra space at the bottom that I cannot seem to remove. Despite trying various solutions from different Stack Overflow threads, such as adjusting chart.marginBottom, chart.spacingBottom, x and yAxis margins, and d ...

Preventing selection of past dates with Material UI in ReactJS

I'm currently working on a date range picker using react material ui. The goal is to allow users to select a specific date and then disable all past dates from that selected date onward. How can I go about implementing this functionality in react mate ...

What is the best way to transfer a row value from one table to another and then reinsert it back into the original table

I attempted to transfer a row value from one table to another and then back to the original table, but unfortunately, I was unable to find a solution. $('#one tbody tr td input.checkbox').click(function() { if ($(this).attr('checked&apo ...

A guide on customizing bar colors in a jqPlot stacked bar graph

Is there a way to customize the colors for individual bars in a jqPlot stacked bar chart? I've searched through examples, but they all seem to use the default colors. How can I explicitly set different colors for each bar? Here is the current code sn ...

Using jQuery UI Tabs to Dynamically Select a Tab Based on a Link

Recently, I have been exploring the idea of using a script to open a specific tab: $('.tofour').click(function() { // bind click event to link $tabs.tabs('select', 3); // switch to third tab return false; }); However, my dilem ...

Angular/Ionic - How can I prevent my function from being called repeatedly while typing in an input field?

I am currently in the process of self-teaching how to construct an Angular/Ionic application. To store JSON, I am utilizing Backand and aiming to retrieve a random JSON value each time the page is refreshed. An issue I am facing is that the random call fu ...

Unable to save object in JavaScript memory

Currently, I am in the process of implementing a Stack in JavaScript using a LinkedList. However, I encountered an issue when trying to instantiate a Node class. When attempting to create a variable let newNode = new Node(x), I am receiving undefined. I a ...

Javascript code not running as expected

Check out this code snippet: function generateRandomTeams() { const prom = new Promise(() => { // ... console.log('teams', props.state.teams) // logs }) .then(() => { console.log('here') // doesn't log }) ...