Displaying only the first date element in a loop using AngularJS, while updating an array object

Currently, I am facing the challenge of displaying a JavaScript object in an Angular ~1.2.24 template.

I want to display only the first occurrence of item.day.

Take a look at this sample object:

$scope.listtrail = [{
    day: '2015-08-15',
    id: 123,
    timestamp: '2015-08-15 12:23:12'
},{
    day: '2015-08-15',
    id: 122,
    timestamp: '2015-08-15 12:43:34'
},{
    day: '2015-08-15',
    id: 121,
    timestamp: '2015-08-15 14:12:56'
},{
    day: '2015-08-14',
    id: 120,
    timestamp: '2015-08-14 11:12:09'
},{
    day: '2015-08-14',
    id: 118,
    timestamp: '2015-08-14 10:11:02'
}]

Here is an example of the desired output template section:

<div ng-repeat="item in listtrail">
    <div>{{item.day}}</div>
    <div>{{item.timestamp}}</div>
</div>

The expected result wanted from the template looks like this:

<div>
    <div>2015-08-15</div>
    <div>2015-08-15 12:23:12</div>
</div>
<div>
    <div>2015-08-15 12:43:34</div>
</div>
<div>
    <div>2015-08-15 14:12:56</div>
</div>
<div>
    <div>2015-08-14</div>
    <div>2015-08-14 11:12:09</div>
</div>
<div>
    <div>2015-08-14 10:11:02</div>
</div>

Please bear in mind that the JavaScript array may grow and get updated periodically by an internal splice function.

Answer №1

A great solution is to incorporate the angular-filter module into your project. Here's how you can implement it:

<div ng-app="app">
  <div ng-controller="TestCtrl">
    <div ng-repeat="(key, value) in listtrail | groupBy: 'day'">
        <div>{{ key }}</div>
        <div ng-repeat="item in value">{{item.timestamp}}</div>
    </div>
  </div>
</div>

For further reference, check out this JSFiddle

Answer №2

<div ng-repeat="item in listtrail">
  <div ng-if="listtrail[$index-1].day !== item.day">{{item.day}}</div>
  <div>{{item.timestamp}}</div>
 </div>

Works perfectly well: https://jsfiddle.net/2o5nwy2r/5/

Consider using $filter for a more robust groupBy functionality in your ng-repeat. Check out angular-filter here: https://github.com/a8m/angular-filter

Answer №3

Make sure to always compare values with the previous day's data

<div ng-repeat="item in listtrail">
  <div ng-if='listtrail[$index -1].day != item.day'>{{item.day}}</div>
  <div>{{item.timestamp}}</div>
</div>

It is important to maintain the chronological order of your records by day.

Check out this jsFiddle

Answer №4

My solution was in line with the others, but I included an additional conditional check for $index == 0:

<div ng-app>
  <div ng-controller="TestCtrl">
    <div ng-repeat="item in listtrail">
      <div ng-if="$index == 0 || listtrail[$index-1].day != item.day" ng->{{item.day}}</div>
      <div>{{item.timestamp}}</div>
    </div>
  </div>
</div>

Although omitting this check doesn't seem to result in an error, it goes against my personal preference.

https://jsfiddle.net/2o5nwy2r/6/

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

creating folding effect using javascript and css with divs

I've been searching high and low on the internet for a solution like this, but so far I haven't had any luck. It seems like there might be a JavaScript script out there that dynamically changes the css -webkit-transform: rotateY(deg) property. ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

Sending information to a dialog box

I'm facing a challenge with my button that triggers a modal. Although the button works fine, I now need to figure out how to pass data from the button to a specific field within the modal. Here is the HTML code: <input type=button value='Add ...

Error encountered in ES6 destructuring syntax

Could you please assist me in figuring out what is causing the issue here: var foo = { bar: 1, baz: 2 }; var { bar, baz } = foo; I encountered an error SyntaxError: Unexpected token {. I am using node v5.4.1 and I am unsure if the problem lies wit ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

What are some strategies for preventing the $window.alert function from being triggered within an AngularJS controller's scope?

How can I prevent the alert from appearing on my dashboard? Do you have any suggestions? Thank you! I attempted to override the alert empty function in my controller, but I am still encountering the window alert when I navigate to my page. $window.alert ...

Converting HTML to PDF using AngularJS

Can anyone help me with converting HTML to PDF in Angular? I have tried using the angular-save-html-to-pdf package from npm, but encountered errors. Are there any other solutions or custom directives available for this task? ...

Building Dynamic Web Applications with Meteor and React

As someone new to Meteor/React, I am currently struggling with creating a multi-page application. I'm particularly confused about how to set up routing effectively. My goal is to have different html files that are rendered based on user interactions. ...

Error encountered while waiting for Angular to finish loading in Protractor: ScriptTimeoutError - Task: Protractor.waitForAngular()

Yesterday went smoothly, but today after updating to pull all commits from svn, everything stopped working. Every time I run a test, I encounter this error: ScriptTimeoutError: script timeout And: From: Task: Protractor.waitForAngular() - Locator: By(c ...

Best practices for initializing Angular 1 code?

My angular web application currently makes a backend API call every time it needs to display the user's name or image. However, I want to start caching this information in localStorage when the app is first launched. Where would be the optimal locatio ...

Executing a loop synchronously within an Angular application

I am grappling with Angular as I have an $http request retrieving multiple rows that need to be processed synchronously. The challenge arises when these records must be processed against a local SQLite database on an iOS device, which involves an asynchron ...

What is the best way to eliminate HTML encoding from a string in Angular 4?

Looking for a simple solution to my problem. I have two strings that look like this: htmlStr = "&lt;strong&gt;News Body&lt;/strong&gt;"; htmlStr1 = "<strong>News Body2</strong>"; To display these strings on a website, I am usi ...

Unleashing the Power of the "OR" Operator in Form Field Validation

The custom JavaScript function FormQuote_Validator is used to validate form fields. It should return the value "TRUE" and display an alert message if all three input fields are submitted without any numbers; otherwise, it should return the value "FALSE". ...

Ideas for showing backslashes in the context of a Cognito filter solution

I need to apply a filtering on Cognito, and the required string format is as follows: "family_name = \"Reddy\"" Currently, I am using `email = "\"${email}"\"` However, when I check the console l ...

Tips for looping through multiple states within a single table

I need help with combining data from two different states, campaigns and stats, into a single table. The campaigns state includes sr no, campaign id, campaign name, and campaign status, while the stats state includes reach, sent, delivered, views, clicks ...

Randomize the array of images in Nuxt every time the page is reloaded to display a variety of logos in the carousel

I've set up a carousel of logos, with the intention to randomize their order every time the page reloads. The challenge is that my layout only allows for 10 images to be displayed at once. While it seems like everything is functioning correctly, I&ap ...

Issue with executing Javascript on a basic HTML webpage

I am attempting to develop a basic app that rolls dice fairly once, and then unfairly afterwards (as requested by a friend in a behavioral studies course). While I have no previous experience with writing JavaScript or HTML, I suspect there might be a begi ...

Modifying the route category through parsing information from a JSON file

As a disclaimer, I must admit that I am venturing into unfamiliar territory here. Due to the ongoing restructuring at my workplace, I am required to take on additional tasks, such as creating visualizations. Here's the issue I'm facing: I have a ...

Issue creating a JWT using jsonwebtoken module in Node.js

Could someone help me troubleshoot an issue I'm having while trying to generate a JWT token? The error message "TypeError: Right-hand side of 'instanceof' is not an object" keeps appearing even though the syntax seems correct. const jsonwebt ...

Is there a way for me to identify a click on a specific element along with all of its child elements, excluding one

I'm attempting to implement a feature where clicking on a specific div triggers a function in JavaScript/jQuery, but I don't want the function to be triggered if I click on a child element of that div. Here's the structure I'm working ...