Filtering an array of objects by a specific parameter in JavaScript

I am working with a variable that contains an array of comments.

$scope.numOfCommentsCoupon

What I want to do is create a variable that counts the number of comments in the array that have a specific "couponId" value.

Here is the structure of the Comment Model:

    var CommentSchema = new Schema({

    created: {
        type: Date,
        default: Date.now
    },
    couponId: {
        type: String,
        trim: true
    }

});

I need to filter through the array and then calculate the count, but I'm unsure of how to accomplish this.

Answer №1

One way to handle an array of comments is by utilizing the following code snippet

let total = 0;
comments.filter(function(response, position, group){
    if (response.promoCode === "special_offer") {
        total++;
    }
});

If preferred, you can also loop through the comments with a for loop. It's a simple method to execute.

Answer №2

It seems like I understand the concept you're aiming for, and one way to achieve it is by utilizing array.filter

Here's an example code snippet:

var targetCouponId = 1;
var results = yourArray.filter(function (item) { return item.couponId === 1; });
console.log(results.length);

Answer №3

To find the count of coupons with a specific couponId in an array, you can utilize the reduce method:

const items = [
    {
        couponId : "xyz"
    },
    {
        couponId : "abc"
    }
];

const targetCouponId = 'abc';

const totalCount = items.reduce(function(previousCount, currentItem) {
    return currentItem.couponId === targetCouponId ? previousCount + 1: previousCount;
}, 0);

console.log(totalCount);

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

Extract the target from the loop in JavaScript and process it externally

I am looking to extract the values from a loop and manipulate them outside of it. Specifically, I want to target all elements with the class "testY" and only apply changes to the last one. let classes = Array.from(document.getElementsByClassName("testY") ...

Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements: const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, ...

What is the best way to categorize elements in an array of objects with varying sizes based on two distinct properties in JavaScript?

I am faced with a scenario where I have two distinct arrays of objects obtained from an aggregate function due to using two different collections. Although I attempted to utilize the map function as outlined here, it proved unsuccessful in resolving my is ...

Learn how to smoothly transfer a URL from JavaScript to HTML and initiate the download process

I created a website that solely relies on HTML5, CSS and JavaScript to function. The core functionality of this website involves utilizing YouTube URLs. I have stored the URL of a specific YouTube video as a variable, now I am looking for a way to transfer ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

Lighting uniformity concept in Three.js

My 3D model needs to be uniformly lit from all angles without any shadows. Currently, I am using a Spotlight, but its directional nature only lights up certain parts of the model at a time. One solution I am considering is to place a spotlight at each cor ...

Activating a inaccessible element

Attempting to enable a disabled element upon clicking a P element, the following code snippet demonstrates storing a value from one textbox into another. The appended div contains a subsequent textbox which will be disabled. On mouseover of the div, option ...

Enhancing the node module of a subpackage within Lerna: A step-by-step guide

I recently integrated lerna into my workflow to streamline the installation of all node modules for multiple sub packages with just one command. Currently, I'm only utilizing the lerna bootstrap feature. Here's a snippet from my lerna.json: { & ...

When the document is fully loaded and processed, a script will be executed immediately following

I'm facing an issue with a modal plugin on my website. The plugin is triggered on $(document).ready, but I have another function (innerHTML) that inserts an <a> element 5-10 seconds after the page loads. This causes the modal not to work properl ...

Lock the "tr" element dynamically at the bottom of the table

Is there a way to keep a specific tr at the bottom of a table using VUE or Js? I have a Vue component that dynamically adds table rows based on an API call. However, I need a specific tr to always be at the bottom, and whenever a new tr is added, it shoul ...

Issue with a hidden div, problem with scrolling, a div overlapping other divs

I'm feeling a bit lost here, trying to figure out what went wrong. It seems like a simple mistake, but I can't pinpoint it. Currently, I'm just testing everything out for a mobile website template. Hopefully, that information helps. For any ...

Unlock the power of viewing numerous inputs simultaneously

Seeking guidance on how to allow users to preview images before uploading them. Currently, my code successfully previews images for one input field, but I am facing challenges when trying to add multiple pairs of inputs and images. How can I implement mul ...

There was an issue retrieving the user with a particular email and status in mongodb

I am trying to retrieve a user order with a specific email and status that is not equal to "Order Completed". However, I am encountering an error stating "Expression $ne takes exactly 2 arguments. 1 were passed in." It would be greatly appreciated if someo ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

Having Trouble Loading a Basic Scene in Three.js

I'm struggling to set up my HTML page with the basic scene because nothing is appearing. I can't seem to locate the required three.js file that I'm supposed to include in my js folder for referencing it as mentioned in the documentation (lin ...

Generating dynamic menu options for a <select> element from an array using React's createElement() method

I have a question about dynamically populating options from an array or JSON. Currently, I am generating the options manually with the following code: return React.createElement("select", {}, React.createElement("option", {value: "A"}, "Option ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

Validation in ASP.Net to ensure the correct number of days between the arrival and departure dates

One of my project requirements involves checking the validation of the number of days entered between two date selectors (From & To Dates). The constraint is that the difference should not exceed 100 days. I'm considering using ASP.NET validators for ...

Exploring the intricacies of incorporating external event handlers in Angular applications

In my current project, I am working on an Angular application that incorporates the Ace editor with ui-ace for text editing on the screen. I am looking to create a function that will execute when the cursor changes, updating a specific model object when th ...