How can we determine the number of duplicate elements in an array?

Is there a way to tally the occurrences of specific words from a list within a given set of phrases and store the count in designated variables?


let counter = [];
let wordToCount = ["tomato","cat"];
let phrasesToCheck = ['my cat like potatoes','cat like apple','my golden fish like tomato'];

counter[0] = 1; //tomato
counter[1] = 2; //cat

Answer №1

let wordsToFind = ["banana", "dog"];
let sentencesToSearch = ['my dog loves bananas', 'my cat likes fish', 'my banana is ripe'];
let allWords = sentencesToSearch.join(' ').split(' ');
let wordCounter = wordsToFind.map(word => allWords.reduce((total, current) => total += current === word, 0));
console.log(wordCounter);

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

Steps to Create a Repeating Melody/Instructions for Implementing a Loop Function

Currently, I am working with discord.js and have had success implementing various commands. However, I am having trouble creating a loop command for my discord bot. This specific command should play a song repeatedly until the loop command is executed ag ...

New example of how to use the "useSession" syntax in Next Auth

Currently, I am delving into the next-auth documentation and feeling perplexed by the syntax used in the useSession hook. The way it's showcased in the documentation is as follows: const { data: session, status } = useSession() My confusion stems f ...

Sort through an array of objects using the Filter API to find objects with matching

I need assistance in dynamically filtering my array based on a condition where values from one array match another static array. The array nfts is dynamic and changes depending on the user. It contains metadata, images, transaction information, etc. Speci ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

What could be causing my directive to not display the String I am trying to pass to it?

Currently attempting to create my second Angular directive, but encountering a frustrating issue. As a newcomer to Angular, I have been studying and referencing this insightful explanation as well as this helpful tutorial. However, despite my efforts, I am ...

Having difficulty linking a click event to an Anchor tag within a React component

Here is the code snippet for ComponentA.js: This is the return statement inside the component return ( ...... <a id="MytoolTip" ...... <ComponentB content={ ` <div class="share_cart_tt ...

Is it possible to show more than five buttons in an Amazon Lex-v2 response display?

Here is the sessionState object I am working with: { "sessionAttributes": {}, "dialogAction": { "type": "ElicitSlot", "slotToElicit": "flowName" }, "intent": { "name": &q ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

Blockage preventing text entry in a textarea

To enhance the basic formatting capabilities of a textarea, I implemented a solution where a div overlay with the same monospace font and position is used. This approach allows for displaying the text in the div with different colors and boldness. However ...

Error: An identifier was unexpectedly encountered while using the Submit Handler

I am currently working on creating a validation script and an AJAX call. I have encountered a problem where the alert message is not working within the if condition. I can't seem to figure out what's causing this issue. When I execute the scri ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Guide: Building Angular/Bootstrap button checkboxes within a loop

I am in the process of designing a grid (table with ng-repeat) in which each row contains 4 columns of buttons. My goal is to use checkboxes as the buttons, like the Angular/Bootstrap btn-checkbox, so that they can be toggled on and off. I plan to set thei ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

Updating an element within a JSON object in PHP: A step-by-step guide

I have a JSON object that looks like this: { "fields" : [ { "name" : "news_title", "type" : "text", "value" : "old title" }, { "name" : "news_co ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...

Scroll to the end of the main div's horizontal position instead of using offset().left

I'm struggling with an issue in my code. <script type="text/javascript"> $(function() { $('ul.nav a').bind('click',function(event){ var $anchor = $(this); /* ...

Redirecting files from the file system to the emulator is not functioning properly

I am new to Phonegap and need help resolving this issue. In my application, I need to redirect to the List.html file when a button is clicked. Here is the code I have written: button1 function test() { window.location="/home/swift-03/phonegapexa ...