Checking for the existence of a date in an array and retrieving its corresponding ID using AngularJS

I need to find the ID associated with a specific date in an array. The code I have tried using includes() is not working as expected.

const results = []; 
angular.forEach(getEventdate, function(value)
{
results.push({id:value.id,event_date:value.event_date}); });

if(results.some(result => result.event_date === current_date)) 
{ 
console.log('date exists!'); 
}

Here is a sample array:

0: {id: 4, event_date: "2019-01-11"}
1: {id: 6, event_date: "2019-01-11"}
2: {id: 7, event_date: "2019-01-11"}
3: {id: 8, event_date: "2017-06-13"}
4: {id: 9, event_date: "2017-06-14"}
5: {id: 10, event_date: "2017-06-21"}
6: {id: 11, event_date: "2017-06-22"}
7: {id: 12, event_date: "2017-06-23"}
8: {id: 13, event_date: "2017-06-26"}
9: {id: 14, event_date: "2017-06-27"}

If the current date exists in the array, I want to retrieve the associated id.

Answer №1

Utilizing ES2015 and above, one has the ability to employ the find method in order to obtain the corresponding id when it is identified, otherwise returning undefined.

const { id } = values.find(item => item.event_date === currentDate) || {};

Answer №2

If you are looking to retrieve the initial instance of a specific date, utilize the find function. However, if you require all instances that match the desired date, opt for the filter method.

For example, with find:

const {id} = results.find(val=>{
   return val.event_date === someDateString;
})

The filter function will generate an array containing all matches for the specified date.

const dates=results.filter(val=>{
    return val.event_date === someDateString;
})

Answer №3

Utilize the $filter function.

var currentDate = new Date();
var filteredDate = $filter('date')(currentDate, 'yyyy-M-d');
var eventID = (array.filter(function(item) {
    return item.event_date === filteredDate;
})[0] || {}).id;

If the date is not found, this will result in undefined.

Make sure to include $filter injection in your controller.

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

Error encountered during execution of Angular application, specifically TS2305 error?

Hello, I am currently running an angular application by using the 'ng serve' command. I encountered the following error: ERROR in src/app/accounts/account-form/account-form.component.ts(29,3): error TS2305: Module '"/home/prasanth/primecas ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

React's useState Hook: Modifying Values

I just started learning about React and React hooks, and I'm trying to figure out how to reset the value in useState back to default when new filters are selected. const [apartments, setApartments] = React.useState([]) const [page, setPage] = React.us ...

Automatic Navigation Disappear in AngularJS

Is there a way to create a fixed navigation menu that automatically hides and shows up like the auto-hide taskbar feature in Windows? I want it to disappear when not in use, but reappear as soon as you move your mouse close to the top of the screen. Any s ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

What is the best way to implement form validation using HTML in the front end of Google Apps Script?

I've written a function to validate user inputs in an HTML form (it's a sidebar on Google Sheets): Credit to Chicago Computers Classes function validate() { var fieldsToValidate = document.querySelectorAll("#userform input, #userform se ...

What could be causing the value not to display in my range slider thumb tooltip?

In a recent project of mine, I implemented a range slider with two thumbs - one for setting the minimum value and one for the maximum value. The goal was to provide users with a visual representation of the range they are selecting by displaying the thumb ...

Can you determine the measurements of the combined image's height and width?

Here is my code: for(var i=1;i<10;i++){ $('#vid_c_'+i).append('<div class="move_2" id="vd'+i+'"></div>'); $('#vd'+i).append('<img class="class" id="id_'+i+'" src="'+_m[i ...

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

The `introJs()` API encounters issues when connected to an element within a jQuery modal dialog box

I am attempting to showcase an Intro.js tour on a specific element located within a <table>. This particular <table> is nested inside a dialog box created using jQuery UI. The rows of the table are dynamically inserted using JavaScript: while ...

Sending data from Django's render() method to React.js

Currently, I'm working on a Django + React Application project where I am faced with the challenge of passing JSON data from Django's render() function to React.js. To achieve this, I initiate the rendering of an HTML page using Django, with the ...

Identifying the difference between var and JSON.stringify

Take a look at this code snippet: var data = JSON.stringify({ id: _id, ReplyId: _idComment }) openDialog(_url, data, $('#div-modal1')); function openDialog(url, Id, div) { //How can we identify if variable Id is of type JSON.stringi ...

Is it possible to choose tags from a different webpage?

Imagine you have a page named a.html which contains all the jQuery code, and another page called b.html that only includes HTML tags. Is it feasible to achieve something like this: alert( $('a').fromhref('b.html').html() ); In essence ...

Read from input file using JavaScript and upload using XMLHttpRequest

Apologies for any language barriers. I am trying to upload my (.exe) file selected using an input file: <input type="file" id="myfile"> Here is how it should be read in Javascript: var myfile=''; var input = document.getElementById(&apos ...

Obtain the inner text input value using jQuery

In my form, there is a feature that adds a new row of text inputs dynamically when a user wants to add more rows. Each new row is automatically populated with input fields that have the same id and class as the previous ones. My question is: how can I re ...

Is there a way in Javascript to apply quotation marks to each value within an array individually?

I've created a function that retrieves and displays values from a CSV file. Here is the code for the function: var IDArr = []; var fileInput = document.getElementById("csv"); readFile = function() { console.log("file uploaded") var reader = new ...

AngularJS docker image that can be reused

Our team has developed an AngularJS application and crafted a dockerfile for it to ensure reusability across different systems. While the dockerfile may not adhere to best practices and could be considered unconventional due to combining build and hosting ...

VueJs Axios - Managing Request Headers

Edit: Is it possible that this is a CORS issue, considering I am on localhost... When using Javascript, I have the ability to define request headers and handle responses like this: $(function() { var params = { // Request parameters } ...