Code snippet: `js: iterating over elements in an array`

Can someone help me with this question? I'm struggling:

  1. Create an array called 'bowl' with the following items:

    ["jelly-bean", "m&m", "m&m", "chocolate", "m&m", "jelly-bean",
    "m&m", "m&m", "jelly-bean"]

  2. Then, declare three variables: jbOccur, mOccur, chocOccur. Set each to 0.

  3. Lastly, write a function named 'occurrence' that iterates through the 'bowl' array and updates the values of the three variables according to their occurrences. (Hint: after running the 'occurrence' function, jbOccur should be 3).

This is what I've come up with so far. Any feedback would be appreciated:

var bowl = ["jelly-bean", "m&m", "m&m", "chocolate", "m&m", "jelly-bean", "m&m", "m&m", "jelly-bean"]

var jbOccur = 0
var mOccur = 0
var chocOccur = 0

var occurrence = function (jbOccur, mOccur, choOccur){
  for (var i = 0; i < bowl.length; i++) {
    console.log(bowl[jbOccur, mOccur, chocOccur])
  }
};

Answer №1

Give this a shot:

let bowl = ["jelly-bean", "m&m", "m&m", "chocolate", "m&m", "jelly-bean", "m&m", "m&m", "jelly-bean"]

const stringOccurrences = (stringArray, toFind) => {
  let occurrence = 0;
  for (let elem of stringArray){
    if (elem.indexOf(toFind) !== -1){
      occurrence++;
    }
  }
  return occurrence;
}

let jbOccur = stringOccurrences(bowl, "jelly-bean");
let mOccur = stringOccurrences(bowl, "m&m");
let chocOccur = stringOccurrences(bowl, "chocolate");

console.log(jbOccur, mOccur, chocOccur);

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

The useEffect hook is causing a loop of API calls after successfully fetching data

I've been working on fetching data from my API and then performing some mappings to present it in the desired format. The challenge I'm facing is that the API calls are asynchronous, so I need to wait for the response before updating my dataset. ...

Using AngularJS ng-repeat to apply several custom filters for sorting items based on properties in a JSON object

Link to JSFiddle for this issue: http://jsfiddle.net/ADukg/16368/. I am attempting to create a filtering system for items in an ng-repeat list based on multiple criteria from the JSON properties of each object. For example, when the 'Unread' fi ...

What is the best way to apply a class to an element in an input template using Angular's ngFocus directive, or any directive incorporated in the Ionic Framework?

I'm working with a template that looks like this: <label class="item item-input" ng-class="{'focus':authData.username.focus}"> <--add class here if input:focus <span class="input-label">Username</spa ...

Opencart now offers a feature that allows for instant quantity updates in your cart

When using standard opencart functionality, users typically have to manually click the update button after adding a product to their cart in order to update the quantity. To see an example of this behavior, visit . However, I would like the cart informatio ...

"Exploring the power of Ruby arrays in multith

I am working on populating an array with responses from API requests using threads to boost efficiency. While I understand that threads aren't truly parallel, they do help speed up the overall process. To ensure order is maintained, I start by creati ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

transform json array into a consolidated array by merging identical IDs

I need to transform an array into a different format based on the values of the ID and class properties. Here is the initial array: const json = [{ "ID": 10, "Sum": 860, "class": "K", }, { "ID": 10, "Sum": 760, "class": "one", }, { "ID": ...

Steps on accessing information from a JSON object using a specific key

Currently, I'm in the process of parsing a JSON file using PHP. My goal is to extract data only from the array where the ID matches 1234. Here's an example snippet: [ { "id":"1234", "is_printed":"1", "is_refunded":"1", ...

You cannot use objects as a React child within the react-stacked-center-carousel component

Using the react-stacked-center-carousel, I have encountered an issue with passing an array of objects to the StackedCarousel component. Here is the link to my reference sandbox: Reference Sandbox I also have a sandbox where I am trying to implement it mys ...

Creating a function inside of setInterval does not refresh

I'm facing an issue with a method that involves the use of setInterval public retrieveMessages(route: string) { this.http.get(this.url + route + "?page=" + MessageService.plus) .subscribe(function(response) { if (response.json.length ...

Is there a more efficient method for translating arrays between JavaScript and PHP?

Currently, I am in the process of developing a web page that has the capability to read, write, and modify data stored in a MySQL database. My approach involves utilizing PHP with CodeIgniter for handling queries while using JavaScript to dynamically updat ...

index.js doesn't quite match the functionality of index.ts

Currently, I'm in the process of developing a web application using angular2 and typescript. I attempted to incorporate index.ts so that in my code, I could simply include import {LayoutComponent} from '../layout'; However, during transpil ...

An efficient way to convert TypeScript's export default into exports = xxx

When working with TypeScript, I typically export a class using the following syntax: export default class World { } However, during compilation, TypeScript transforms it into: exports.default = class World { } Is there a way to compile it to be like th ...

Extracting the value of a pipeline property using PowerShell

I'm trying to figure out why I can retrieve the value for the Website but not the WebServer using this command. Can somebody help me understand? Here is what $DeploySetting.setting looks like: Name-------------Value Website----------XXXXX WebServe ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...

Tips for integrating Node/Express into a local application to seamlessly stream local video files on an HTML5 player

I am currently working on developing an HTML5 video player specifically designed for local use, rather than online streaming. My approach involves utilizing Node.js and Express, although I do consider myself a novice when it comes to Node. So far, I have m ...

Is this filter selector in jQuery correct?

It appears to function correctly, but I am unsure if there is room for improvement. I aim to target any HTML element with a class of edit-text-NUM or edit-html-NUM and adjust its color. This is the code snippet I am currently utilizing... jQuery(document ...

Code for remotely connecting to a server and starting a Node.js application called app.js via SSH

I am attempting to establish an SSH connection to two servers sequentially in order to execute the following command: sudo node app.js This is the code I am using: #!/bin/bash while read line; do ssh -i "sshtest.pem" ec2-user@$line "sudo node app. ...

Is it feasible to retrieve an object from AWS S3 in Blob format using AWS SDK for JavaScript V3?

Currently, I am working on a project utilizing Next.js and I am facing the task of uploading photos to a Bucket S3. In order to stay up-to-date with the latest technology, I have chosen to utilize the latest version (3) of AWS SDK for JavaScript. After se ...

Is it possible to create an instance of a superclass and automatically instantiate a specific subclass based on the parameters provided?

Currently, I am utilizing Google's GSON package which can be found at this link My task involves converting JSON data to Java objects. Below is a snippet of the code where the conversion process takes place: Gson gson = new Gson(); Type collectionT ...