Find the frequency of a specific string within a JSON array

My current task involves working with a stringified array:

JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]

I must determine the frequency of occurrences of the word "yellow" within this data in order to proceed with the following operations:

numYellow = 0;
for(var i=0;i<arr.length;i++){
  if(arr[i] === "yellow")
  numYellow++;
}

doSomething = function() {
  If (numYellow < 100) {
    //do something
  }
  If(numYellow > 100) {
    //do something else
  } else { do yet another thing} 
}

Answer №1

Every item in the array represents an individual object. To update, switch from using arr[i] to instead reference arr[i].color. However, it is important to note that this change is based on the assumption that the only occurrence of the color yellow will be within the .color property.

Answer №2

Here is a solution that might work:

let shapes = [{"x":7.52,"y":3.94,"color":"orange","restitution":0.5,"type":"dynamic","radius":2,"shape":"circle","width":0.4,"height":0.4},{"x":8.75,"y":5.21,"color":"orange","restitution":0.5,"type":"dynamic","radius":2,"shape":"circle","width":0.4,"height":0.4}]

let numOrange = 0;

for(let j=0; j<shapes.length; j++) {
    if (shapes[j].color === "orange") {
        numOrange++;
    }
}

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

Edit images prior to uploading to the server by adjusting the size or dimensions as raw binary data (format should be either png or jpeg

In my quest to crop images in the browser and upload them directly to a server as raw image binary data (either in "image/jpeg" or "image/png" format), I have tried various client-side methods for cropping and uploading. These methods typically utilize the ...

Create an Interactive Data Visualization with JSON using CanvasJS Charts

Having some trouble creating a chart using CanvasJS. After fetching data from the API and checking the JSON array, I encounter two errors when attempting to generate dataPoints for the graph: "data invalid" on the data field and "NaN" on the value field. ...

Tips for submitting JSON data to the specified input area with AngularJS

I have a json object that looks like this: var jsondata = { "id": 1, "name": "Test Name", "price": 100, "city": "XYZ" }; I am trying to post/send this data to a specific url location when the Send button is clicked. The url location can be entered in an ...

What is the best way to retrieve specific JSON information?

[["pdf-sample.pdf",["uploads\/28\/pdf-sample.pdf"],{"en":"PDF Sample"},"","28"],["pdf-sample2.pdf",["uploads\/29\/pdf-sample2.pdf"],{"en":"Second PDF sample"},"","29"]] After figuring out how to access the uploads\28\pdf-samp ...

Sending JSON data from an iOS app to a Flask backend

Within my Flask Python web application, I store certain parameters in SessionStorage to later send back to Flask and save this data as a text file. Interestingly, the process functions perfectly on PCs and Android devices but encounters issues on iOS devi ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...

Developing an Android app that communicates with an ASP.Net Web API using Java programming

I'm currently facing difficulties in setting up the HttpPost method correctly. I have developed an ASP.Net web api with mvc 4 and now I am attempting to fetch data from one of the controllers in my android app. Below is the code snippet in Java for An ...

Having trouble sending AJAX select options with Choices.js

I'm currently utilizing Choices.js (https://github.com/jshjohnson/Choices) along with Ajax to dynamically populate data into my select field from a database. However, I've encountered an issue when using the following code: const choices = new C ...

What could be causing UserAuthExtensions.PopulateFromMap(session, jwtPayload) to fail in properly deserializing escaped JSON values within ServiceStack.Auth?

Our goal is to extract the UserName from the ServiceStack session, but we're encountering an issue with the deserialization of backslashes in the UserName. The UserName follows this format 'domainname\username', and when serialized in a ...

Guide to creating a contenteditable div that automatically generates smart quotes instead of traditional dumb quotes

I've observed that when I write in Google Docs, I get smart quotes. However, when I create contenteditable divs on my own, I only see dumb quotes. Is there a way to make my contenteditable divs display smart quotes instead of dumb quotes? ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Delete the element that was generated using jQuery

Is there a way to add and remove an overlay element using JavaScript? I am struggling to get JavaScript to remove an element that was created with JavaScript. Any suggestions? Check out this JS Fiddle example Here is the HTML code: <div id="backgroun ...

Utilizing typesafe trpc in Node.js to efficiently transfer data between routes

I have successfully implemented an end-to-end typesafe API using the T3 Stack and can access all the data and types in my Next.js app. However, I also have a Node.js backend to populate my database with. My Node.js setup is as follows: app.use( '/t ...

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a r ...

Which is the better choice: SQL or JSON?

For storing information like comments on my website, I currently rely on JSON databases instead of SQL. While I'm comfortable with SQL, I find JSON more user-friendly. Should I consider transitioning to SQL despite my preference for JSON? ...

Having an issue with jQuery where trying to append a remove button to a list results in the

Looking to create a dynamic list where users can easily add new items by clicking a button. As each item is added, a corresponding remove button should also be displayed. The issue I'm facing is that every time a new item is added, an extra close but ...

Making a POST request using axios in a MERNStack application

After successfully using the express router to add articles with Postman, I encountered an issue when trying to send article information through Axios to MongoDB. Despite no errors appearing in the console, there was a message stating "SharedArrayBuffer ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

Arrange the columns in Angular Material Table in various directions

Is there a way to sort all columns in an Angular material table by descending order, while keeping the active column sorted in ascending order? I have been trying to achieve this using the code below: @ViewChild(MatSort) sort: MatSort; <table matSort ...