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

AngularJS version 1.2.0 is experiencing an issue where the $http service is not properly sending requests

Why is AngularJS 1.2.0 $http not sending requests in $eval? Here is the code you can refer to: http://jsbin.com/oZUFeFI/3/watch?html,js,output ...

What is the best way to assign individual instance variable names in bulk while looping through and parsing an array of hashes?

Starting with a refined big hash that includes various details about a company. angel_hash = {"follower_count"=>1369, "name"=>"AngelList", "markets"=> [{"display_name"=>"Startups", "name"=>"startups", "id"=>448, "tag_type"=>"MarketTag ...

The kendo-ui numeric textbox is malfunctioning when set with a step value of 0.001

Having some issues with the Kendo UI numeric text box. Specifically, it doesn't seem to work properly when using a step value of 0.001. In the example code snippet below, I managed to get it to increment by 0.001 with HTML5 but couldn't make it w ...

"Ensuring Username Uniqueness in AngularJS and CakePHP3: A Step-by-Step

<input type="email" id="username" dbrans-validate-async="{unique: isUsernameUnique}" ng-model="username" required class="form-control" name="username"> $scope.isUsernameUnique = function(username) { $http.get(url+'/isUsernameUnique&apo ...

Events in d3.js are properly registered, however they are not being triggered as

After creating an enter section that transitions to set the opacity to 1, I encountered an issue where the 'click' event on the circle worked but not on the text. Interestingly, when I replaced the 'text' with a 'rect' and se ...

Import a precise model from a glb file

Greetings! I am relatively new to working with ThreeJS and just getting the hang of it. After going through some tutorials, I have successfully managed to load glb files and render them in my browser with ease. Recently, I downloaded a GLB file from that ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

How to verify changes in session variable using PHP and AJAX

Hey there! I'm looking for a way to continually monitor changes in a session variable within PHP. Let's say the session variable "x" starts off with a value of "1" and then, after five seconds, it changes to "2". This session variable "x" is up ...

Upload a high-quality canvas image (dimensions: 1800px x 1080px) to a server with the help of asp.net

I am facing an issue with saving a canvas image to the web server. The problem arises when the image size exceeds 200x200 pixels and has high resolution – it fails to save in such cases. Saving a smaller image works fine, but larger images with high re ...

Preventing request interceptors from altering the request header value in Node.js

I am currently using the http-proxy-middleware to set up a proxy, and it is working smoothly. However, before I apply app.use('/', proxy_options);, I am attempting to intercept my request and update the request header. Unfortunately, the changes ...

"Return to previous view with the zoom back feature in CanvasJS

How can I implement a zoom back button in CanvasJS using jQuery or normal JavaScript? I've been attempting to place it near the ones in the top right corner, but something seems to be amiss. Alternatively, is it feasible to enable zooming in and out ...

The issue with jquery slideToggle is that it mistakenly opens all divs instead of just the specific div that should

My website has a dynamic page with a variable number of <div> elements. The concept is that users can click on the + symbol, which is represented by an <img> tag, to display the corresponding div. Currently, my code includes: PHP/HTML $plus ...

A strategy for concealing the selected button within a class of buttons with Vanilla JS HTML and CSS

I have encountered a challenging situation where I am using JavaScript to render data from a data.json file into HTML. Everything seems to be functioning correctly, as the JSON data is being successfully rendered into HTML using a loop, resulting in multip ...

Subpar resolution of PNG images displayed in HTML canvas

My attempt to draw a PNG image onto the canvas is resulting in poor quality. I am using the drawImage method as shown below: src = folder+self.cur+".png"; imageObj.src = src; imageObj.onload = function() { context.clearRect(0, 0, cv, ch), context.drawImag ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

Arranging an Array of Objects in JavaScript by dual criteria

In my JavaScript code, I have an object structured like this: myArray[0] -> 0:"62", 1:8, 2:0, 3:"11" myArray[1] -> 0:"62", 1:8, 2:0, 3:"15" myArray[2] -> 0:"48", 1:8, 2:0, 3:"04" myArray[3] -> 0:"48", 1:8, 2:0, 3:"01" myArray[4] -> 0:"62", ...

Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an iss ...

Identify and automatically switch to the mobile site following a selection

Seeking a way to incorporate a redirect on my Joomla site that leads users to a mobile-friendly HTML5 app. After much thought, I've put together the following script: <script type="text/javascript> <!-- if (screen.width <= 800) { ...

Transferring the values of JavaScript objects to HTML as strings

My goal is to generate HTML elements based on the values of specific JavaScript objects that are not global variables. However, when attempting to execute the code below, I encounter an error stating "params is not defined." What I actually aim to achieve ...

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...