Extract information from an array using JavaScript

When working with highcharts, I need to generate parsed data to create series. The API data is structured like this:

[ date : XX,
  series : [
            player_id : 1,
            team_id : 1,
            score : 4 ],
            [
            player_id : 2,
            team_id : 4,
            score : 1 ],
            [
            player_id : 4,
            team_id : 1,
            score : 4 ]

],
[ date : XX+1 
  series : ...
], 
...

Firstly, the user must select a team and players, but sometimes there may not be any results. For instance, when selecting 4 team IDs for date XX, the API might only return 2 of them, which needs to be taken into account. I’m trying to create different types of series - one for overall team scores, another for player scores, and more for individual team scores. This leads to multiple graphs being generated.

I am utilizing Ampersand.js, where the model remains constant but is called as many times as the number of teams selected in the form.

The function that I've implemented looks something like this:

function parse(data) {
    var series = [];
    var dates = [];
    var findIndexByValue = function(arraytosearch, key, valuetosearch) {
        for (var i = 0; i < arraytosearch.length; i++) {
            if (arraytosearch[i][key] == valuetosearch) {
                return i;
            }
        }
        return null;
    }

    // Rest of the original code goes here...

}

While generating series, I encountered an issue when there are no results for a specific team in the API response.

An ideal array structure would resemble something like this:

series: [{
    name: 'Team 1',
    data: [4163, 5203, 6276, 5408, 3547, 3729, 3828,4163, 5203, 6276, 5408, 3547, 3729, 3828,4163, 5203, 6276, 5408, 3547, 3729, 3828]
    }, 
    {
    name: 'Team 2',
    data: [...]
 }]

Furthermore, I noticed some redundancy in the code. Is there a clever way to simplify this using Array functions?

Thank you in advance, as this has been quite a challenge for me!

Answer №1

Have you had success with your code implementation? I just tested it out here: http://jsfiddle.net/ma50685a/5/ - the results were a bit unexpected.

In any case, my suggestion would be to enhance your conditional statements, like this:

            var index = findIndexByValue(array, "key", value);

            if (index === null) {
                array.push({
                    key: value,
                    data: [tempData, current.average]
                });
            } else {
                array[index].data.push([tempData, current.score]);
            }

This can all be combined into a single function:

function manageArray (array, name, key, xVal, yValName) {
            var index = findIndexByValue(array, name, current[key]),
                newObj = {};

            if (index === null) {
                newObj[name] = current[key];
                newObj.data = [tempData, current[yValName]];
                array.push(newObj);
            } else {
                array[index].data.push([tempData, current[yValName]);
            }
}

Then simply use it like this:

if (this.currentType === "allTeamSeries") {
    manageArray(series, 'team', 'team_id', tempData, 'average');
else if (this.currentResource === "playerSeries") {
    manageArray(series, 'player', 'player_id', tempData, 'score');
} else if (this.currentTeam === current.team_id) {
    manageArray(series, 'site', 'site_id', tempData, 'score');
}

Please note that this code has not been thoroughly tested due to limitations in setting up a demo based on the information provided. Apologies for any inconvenience.

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 mechanism does the useState() function utilize in React to fetch the appropriate state object and function for a functional component when employing the state hook?

Currently focusing on deepening my understanding of the useState hook in react. I have a question regarding how useState retrieves the state object and modifier function specific to each functional component when it is called. What I'm wondering is w ...

Tips for adjusting the up and down controls and spins of a date input after modifying its height

After adjusting the height of my inputs (date type) to 40px, I noticed that the up and down controls are no longer aligned with the text inside the field. I am looking for a solution to either adjust the height of the spins or remove them if necessary in ...

Trouble with Directive - the watch function isn't functioning as expected

After spending countless hours and trying almost everything, I can't seem to get it to work... I have an Angular directive that calls another Angular directive. I need to handle events in the child directive. So my child directive looks like: ...

javascript/jquery concatenate all hidden input values into a variable

I am working with a collection of tags that are each added to a hidden input labeled "item[tags][]". <input type="hidden" style="display:none;" value="first" name="item[tags][]"> <input type="hidden" style="display:none;" value="second" name="ite ...

Implementing a time delay in the jQuery keyup() function following an Ajax request

I am currently facing a complex issue and I am uncertain about the best approach to tackle it. I have multiple textboxes lined up in a row that need to be filled in. Each time a value is entered into a textbox, I make an Ajax call to process that value. De ...

What are the best methods for testing REST API and Client-side MVC applications?

When dealing with a RESTful server that only responds with JSON data fetched from a database, and having a client-side application like Backbone, Ember or Angular, where should application testing take place? Is it necessary to have two sets of tests - on ...

Navigating through scroll bars in Reactjs

Currently, I am working on developing a React application, and I want to incorporate a full-screen title page as one of its key features. The challenge I am facing is related to the scrolling behavior on the title page. My goal is to have the page automati ...

Sliding an image from the left side to the right, and then repeating the movement from left to right

I am currently working on a CSS effect for some images. My goal is to have an image appear from the left side, move towards the right side, then reappear from the left and repeat this cycle. I managed to achieve this using the code below: @keyframes sli ...

steps to attach click event to row of a-table component in ant design vue

Here is the code snippet for the table I am working on. I have imported a-table from antd. To enable click functionality to route to a details page from this listing page, an additional td can be added. <a-table :columns="companiesColumns" :d ...

Error encountered with MobileFirst version 8 and Angular JS v1.5.3 integration using Bootstrap

I am encountering an issue with my Cordova application that integrates with MobileFirst Platform version 8, Ionic version 1.3.1, and AngularJS version 1.5.3. Upon bootstrapping AngularJS to connect the app to MobileFirst Platform, I encounter the following ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Unable to submit POST request in Node.js

Seeking assistance to resolve a persistent error that has been causing me trouble for quite some time. This issue is preventing me from adding data to my database successfully. Any help or guidance on this matter would be greatly appreciated. This sectio ...

Error: Unspecified (reading 'map'). Utilizing '&&' triumphs in compiling but results in no array being shown

As a beginner student in next-js, I am currently focused on learning about databases and calling arrays. In the files structure & script provided (in this image), I am attempting to call arrays from /data. The issue with the script is that it is ...

Exploring the Functions and Applications of Headers in Javascript

After completing a project which involved updating a JSON database from the front end, I am still uncertain about the role of the headers within the AxiosConfig. Can you explain the difference between using axios with and without it? For instance: What s ...

Guide to importing a JSON file into Vue.js and HTML

I'm a beginner in Vue and not very familiar with HTML I'm attempting to import data from a JSON file into my interface to display it for the user. Below is the structure of the JSON: [ { "Title": "SOFT-STARTER", "Cod&q ...

Steps to include a jQuery reference in a JavaScript file

I'm looking to create an external JavaScript file with validation functions and incorporate jQuery into it. Can anyone provide guidance on how to accomplish this? I attempted the code below, but unfortunately, it doesn't seem to be functioning c ...

I am having trouble setting an object in the state using React hooks

When assigning an initial value to a state as null, the setState method does not hold the value when assigned. Calling an API in useState returns an object which cannot be directly put into setState. const [userProfile, setProfile] = useState(null); cons ...

What is the best way to send the link's ID to an AngularJS controller?

I have a scenario similar to the following: <a href="#" title="Post 1" id="car1"> Audi car </a> <a href="#" title="Post 1" id="car2"> BMW car </a> How can I pass the ID to the controller? I attempted the following: <a href= ...

Implementing JSON data retrieval in Django through jQuery

i have implemented a jQuery functionality to send json data containing arrays of elements as shown below $('#brand_category').click(function(event){ category = $("input:checkbox[name=category]:checked").map(function() { return t ...

Having trouble retrieving an item from an included partial in an EJS template

I am currently facing an issue with sending an object to the aside menu, which is present in all the EJS templates within my application. There are a total of 10 EJS templates that are rendered by 10 different router endpoints. Here's an example of h ...