Using JavaScript, locate the previous and next elements in the JSON array of objects based on the given current event ID

Task: To retrieve and display data based on the current event ID from a JSON file:

var _getEventById = function(eventId) {

        var __findEvent = function(event) {
            return event.id === eventId;
        };

        return _.find(data.meeting.events, __findEvent);
    };

I am attempting to find the previous and next event numbers using the current event ID. The following code, which is placed inside the model, is not functioning as intended.

  var _getNextEvent = function(eventNumber) {
  var nextEventNumber = data.meeting.events.number += eventNumber ;
  var nextEvent = _.find(event, function(event) {
    return event.number === nextEventNumber;
  });

  return nextEvent.id;
};


var _getPrevEvent = function(eventNumber) {
  var prevEventNumber = data.meeting.events.number -= eventNumber ;

  var prevEvent = _.find(event, function(event) {
    return event.number === prevEventNumber;
  });

  return prevEvent.id;
};

My approach involves passing the current event's ID to find the event number using Lodash and incrementing it by one to find the next event's number, then returning its ID. (Similarly, decrementing to find the previous event's ID)

JSON: "meeting": {
      "id": "SING_74",
      "name": "Singapore Racing",
      "runDate": "2017-10-04",
      "meetingNumber": 12,
      "closeDate": "2017-10-04",
      "open": true,
      "venue": "Overseas",
      "currentRaceId": "SING_74_2",
      "code": "RACE",
      **"events": [**
        {
          **"id": "SING_74_1",**
          **"number": 1,**
          "open": false,
          "status": "Closed"
        },
        {
          "id": "SING_74_3",
          "number": 3,
          "open": true,
          "status": "Open"
        },
        {
          "id": "SING_74_4",
          "number": 4,
          "open": true,
          "status": "Open"
        },
        {
          "id": "SING_74_5",
          "number": 5,
          "open": true,
          "status": "Open"
        },

Goal: My objective in Angular is to enable users to swipe on the Racing/events and detect ng-swipe-left and ng-swipe-right gestures to update the data with the next event ID or previous event ID.

If you have any insights or examples to share, they would be greatly appreciated.

Answer №1

To begin, start by generating an array of IDs

let eventIDs = data.meeting.events.map(function(event){return event.id;});

Once you have the array of IDs, determine the index of the current ID and calculate the previous and next IDs:

Math.min() will give you the smallest value. So, if you are at the end of the array and swipe once more, it will return the last index of the array (eventIDs.length-1), since it will be smaller than currentIDIndex+1

currentIDIndex - 1 < 0 ? 0 : currentIDIndex - 1
ensures that the previous index of the array is never below zero

let currentIDIndex = eventIDs.indexOf(currentID);
let previousIndex = currentIDIndex - 1 < 0 ? 0 : currentIDIndex - 1;
let nextIndex = Math.min(eventIDs.length - 1, currentIDIndex + 1);

Lastly, retrieve the event number for the previous and next events

 let previousNumber = data.meeting.events[previousIndex].number;
 let nextNumber = data.meeting.events[nextIndex].number;

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

What is the process for publishing an npm package to a Nexus group repository?

After installing Nexus Repository Manager OSS version 3.2.1, I successfully ran it on my local machine. Setup Within Nexus, I have set up three NPM repositories: [PUBLIC] - acting as a proxy for the public npm registry [PRIVATE] - designated for my own ...

Create a unique key dynamically based on a specified scope value using AngularJs

I am working with an angular directive that utilizes a title with a key from a messages.properties file. To dynamically generate the key, I want to concatenate 'root.' + scope.value + '.title' like so: titre="{{ 'flux.' + &ap ...

Error arises when uploading csv files to Node.js with Multer due to an unexpected field presence

I'm currently working on implementing a file upload feature with the use of Node.js, Vue, and Multer. Below is the Vue.js front-end code: export default { data(){ return{ selected: "How do you want to input the data?", options: [ ...

Top solution for live chat between server and client using jQuery, Java, and PHP on a localhost setup

Seeking recommendations for the best chat solution to facilitate communication between client PCs and a server in my private network. Specifically interested in an Ajax/Java solution similar to the chat support feature found in GMail. ...

Switch out bootstrap icons for angular material icons

I'm currently in the process of transitioning from using Bootstrap to Angular Material in an existing application. I need assistance with replacing the Bootstrap icons with Angular Material icons. Any help is greatly appreciated. <md-button class= ...

Create and exhibit flawless and optimal React JavaScript code following industry best practices

I recently wrote the code below in my React application (file name: SearchBox.jsx): import React from 'react' import ReactDOM from 'react-dom' import $ from 'jquery' export default class SearchBox extends React.Component { ...

When using jQuery AJAX to Like/Dislike, a 500 (Internal Server Error) is returned, but the functionality works correctly upon reloading the

My website has a feature where users can press a Like Status button that uses AJAX to send data to the controller. When the button is clicked, it changes from "like" to "dislike" and all associated classes and form actions are updated accordingly. The is ...

AngularJS: A Step-By-Step Guide to Adding Two Values

Currently, I am utilizing the MEAN stack for my application with AngularJS as the front-end. I have two tables in which I obtained total sum values like 124.10 in the "conversion rate" column. Now, I am looking to calculate the total sum of the "conversion ...

Executing JavaScript Function on the Server Side

Recently, I created a JavaScript function that looks like this: function ShowMsg(msg) { $.blockUI({ message: '<div dir=rtl align=center><h1><p>' + msg + '</p></h1></div>', css: { ...

Exchange SMS messages between server and web application

I'm currently based in Kenya and finding the pricing of Twilio to be quite high. My goal is to send and receive SMS messages, save them in a database, and showcase them on a web app. Do you think it's possible to create this using node.js? What w ...

Utilize mongoose to import data from the file named file.json

I'm having trouble figuring out how to import data from multiple json files using mongoose. Currently, I am importing the files with mongoDB commands: mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray Is there a wa ...

Exploring options for accessing Google Maps API on iPhone without using UIWebView for processing JavaScript

I need to retrieve data from Google Maps using JavaScript, without using a webview. For example, I have two points (lat,lng) and I want to use the Google Maps API to calculate the driving distance between them. Essentially, I want to utilize the Google Ma ...

An effective method for modifying the active class on an li element in jQuery and ensuring that the user is directed to the desired page upon clicking the li element

I am facing an issue with my script tag. When I click on the links test.php or test2.php, the active class changes from index.php to the respective file but I am not redirected to the clicked page. I have tried solutions from various sources but none of th ...

Using the input method in JavaScript cannot extract an object property

Recently, I have been working with this JavaScript code provided below. It is essential for me to retrieve the votecount for a game based on user input. function Game(gamename,votes) { this.gamename = gamename; this.votes = votes; }; var lol = ne ...

Unleashing the power of plugins and custom configurations in your next.js next.config.js

const optimizeNext = require('next-compose-plugins'); const imageOptimization = require('next-optimized-images'); const config = { target: 'serverless', }; module.exports = optimizeNext([imageOptimization], config); tra ...

I am having trouble specifying a class within an SVG using D3.js

I have been facing a strange issue with my script. When I try to execute the following code: var key="#US" d3.select(key).style("fill", "red"); it seems like it's not working for me. Interestingly, when I run the same co ...

Generate a JSON representation of a class within a Spring application

I'm a beginner with Spring and I'm looking to modify the JSON response of my class. public class Mapping { public String name; public Object value; } I want the current format: {"name" : 'value of field name', "value&q ...

Creating objects by iterating through complex nested JSON elements in Ruby on Rails

Currently, I am parsing JSON data from a source that contains mixed content and attempting to save it using ActiveRecord. As of now, my approach involves using numerous variables: json['settings']['newsletters']['weekly'] js ...

Exploring the depths of intricate JSON nesting using Python 3.6.8

I have come across several questions on "nested JSON in Python", but I am facing syntax issues with this COVID-19 JSON data. Here is a snippet: {"recovered":524855,"list":[ {"countrycode":"US","country" ...

The execution of consecutive Ajax requests encounters issues in the Google Chrome and Safari browsers

I am facing an issue where I encounter a problem displaying a sequence of dialogue or AJAX results that depend on each other. For instance, when a user clicks to send a message, it triggers an ajax call, which opens a dialogue box. The user fills out the f ...