Manipulate and edit an array using JavaScript

Currently, I am working on a project in Javascript that involves processing a .dat file containing various data related to English Soccer teams. After extracting a Json from the file, I converted it into an array as follows:

[{"team":"Arsenal","f":"79","a":"36"},
{"team":"Liverpool","f":"67","a":"30"},
...
{"team":"Leicester","f":"30","a":"64"}]

This array contains the names of different soccer teams along with two values: goals scored (F) and goals conceded (A). The task at hand is to parse this array and perform the following operations:

  1. Calculate the difference between "a" and "f" for each team and add this value to the array;
  2. Determine the team with the smallest difference between goals scored and conceded.

However, I am currently stuck and unsure how to proceed with these operations.

I have managed to write some code up to this point:

const myFrom = document.getElementById("myForm");
const datFile = document.getElementById("datFile");

function fileToArray(text) {
    ...
}

myForm.addEventListener("submit", function (e) {
    ...
});

<form id="myForm">
    <input type="file" id="datFile" accept=".dat" />
    <br />
    <input type="submit" value="Submit" />
</form>

Unfortunately, this is where I hit a roadblock in my progress.

Answer №1

For a cleaner writing approach, both of these operations can be combined to achieve the desired result:

Map function is used to calculate and add the absolute difference between two properties as a new property called d.

The Math.abs function is implemented to ensure that the calculated difference is always positive.

let teams = [{"team":"Arsenal","f":"79","a":"36"},
{"team":"Liverpool","f":"67","a":"30"},
{"team":"Manchester_U","f":"87","a":"45"},
{"team":"Newcastle","f":"74","a":"52"},
{"team":"Leeds","f":"53","a":"37"},
{"team":"Chelsea","f":"66","a":"38"},
{"team":"West_Ham","f":"48","a":"57"},
{"team":"Aston_Villa","f":"46","a":"47"},
{"team":"Tottenham","f":"49","a":"53"},
{"team":"Blackburn","f":"55","a":"51"},
{"team":"Southampton","f":"46","a":"54"},
{"team":"Middlesbrough","f":"35","a":"47"},
{"team":"Fulham","f":"36","a":"44"},
{"team":"Charlton","f":"38","a":"49"},
{"team":"Everton","f":"45","a":"57"},
{"team":"Bolton","f":"44","a":"62"},
{"team":"Sunderland","f":"29","a":"51"},
{"team":"Ipswich","f":"41","a":"64"},
{"team":"Derby","f":"33","a":"63"},
{"team":"Leicester","f":"30","a":"64"}];

teams.map((t) => t['d'] = Math.abs(t.f - t.a))

console.log(teams);

To identify the team with the lowest difference, you can utilize the following code snippet along with the reduce function:

    let teams = [{"team":"Arsenal","f":"79","a":"36"},
    {"team":"Liverpool","f":"67","a":"30"},
    {"team":"Manchester_U","f":"87","a":"45"},
    {"team":"Newcastle","f":"74","a":"52"},
    {"team":"Leeds","f":"53","a":"37"},
    {"team":"Chelsea","f":"66","a":"38"},
    {"team":"West_Ham","f":"48","a":"57"},
    {"team":"Aston_Villa","f":"46","a":"47"},
    {"team":"Tottenham","f":"49","a":"53"},
    {"team":"Blackburn","f":"55","a":"51"},
    {"team":"Southampton","f":"46","a":"54"},
    {"team":"Middlesbrough","f":"35","a":"47"},
    {"team":"Fulham","f":"36","a":"44"},
    {"team":"Charlton","f":"38","a":"49"},
    {"team":"Everton","f":"45","a":"57"},
    {"team":"Bolton","f":"44","a":"62"},
    {"team":"Sunderland","f":"29","a":"51"},
    {"team":"Ipswich","f":"41","a":"64"},
    {"team":"Derby","f":"33","a":"63"},
    {"team":"Leicester","f":"30","a":"64"}];
    teams.map((t) => t['d'] = Math.abs(t.f - t.a))
    
    // Identify the team with the lowest difference
    
    let result = teams.reduce((teamA,teamB) => teamA.d > teamB.d? teamB: teamA );

    console.log(result);

Answer №2

One effective way to tackle this problem is by utilizing either a loop (like for...of) or employing array methods such as map for the first part and filter for the second.

Personally, I find using loops more favorable due to its readability and ease of debugging, allowing for the integration of both steps within a single loop. For example:

// Initialize with the first element then iterate through the array
let leastDiff = Math.abs(myArray[0].f - myArray[0].a);
let bestTeam = myArray[0].team;
for (let item of myArray) {
  item.diff = Math.abs(item.f - item.a);
  if (item.diff < leastDiff) {
    leastDiff = item.diff;
    bestTeam = item.team;
  }
}
console.log(`The team with the smallest goal difference is ${bestTeam} with a difference of ${leastDiff}`);

Answer №3

To find the team with the smallest goal difference, you can use a combination of map and reduce:

const teams= [{"team":"Arsenal","f":"79","a":"36"}, {"team":"Liverpool","f":"67","a":"30"}, {"team":"Manchester_U","f":"87","a":"45"}, {"team":"Newcastle","f":"74","a":"52"}, {"team":"Leeds","f":"53","a":"37"}, {"team":"Chelsea","f":"66","a":"38"}, {"team":"West_Ham","f":"48","a":"57"}, {"team":"Aston_Villa","f":"46","a":"47"}, {"team":"Tottenham","f":"49","a":"53"}, {"team":"Blackburn","f":"55","a":"51"}, {"team":"Southampton","f":"46","a":"54"}, {"team":"Middlesbrough","f":"35","a":"47"}, {"team":"Fulham","f":"36","a":"44"}, {"team":"Charlton","f":"38","a":"49"}, {"team":"Everton","f":"45","a":"57"}, {"team":"Bolton","f":"44","a":"62"}, {"team":"Sunderland","f":"29","a":"51"}, {"team":"Ipswich","f":"41","a":"64"}, {"team":"Derby","f":"33","a":"63"}, {"team":"Leicester","f":"30","a":"64"}]

let diff=Infinity;
console.log(
  teams.map((t)=>(t.d=t.a-t.f, t))
  .reduce((a,c)=>Math.abs(c.d)<=diff?(diff=Math.abs(c.d), c.team): a,'')
);

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

Angular 2 encountering CORS issues on Chrome

When I attempt to access a SOAP webservice deployed on WebLogic and developed in Java using JAX-WS, I encounter an issue where IE11 successfully retrieves the response while Chrome returns the following error: Response to preflight request doesn't pa ...

Edit HTML and CSS in live mode while also running JavaScript for instant enhancement

Recently, I created a script that allows me to build a web page in real-time. I can input HTML and CSS codes without any issues, but unfortunately, I am unable to execute JavaScript due to the limitations of the string-based editor I am using. Can anyone o ...

Utilizing Ajax in conjunction with the func_get_args() function

Can php's func_get_args() be used to capture 'post(ed)' data from an Ajax function call? (Currently using json to post data). Example of a hypothetical Ajax call posting data: . url: '.../.../...?action=function' data: { someStri ...

Preserve the order of objects in JSON output in Python

class MessageCreator: def serialize(self,obj): return json.dumps(obj,sort_keys=False,indent=None, separators=(',', ':')) def createGroup(self,name,description,masterkey): return self.serialize({ ...

Using arrays as data in an Ajax request for DataTables

Struggling to send selected row IDs to an API using the DataTables Ajax option. Despite numerous attempts, I can't seem to get the IDs sent as an array. Below is a sample code I've tried. It generates the URL: getStatistics.php?ids=1&ids=2& ...

What is the best way to enable this JavaScript function exclusively for a particular width?

Is there a way to make this javascript function active only when the screen width is at least 1070px? Currently, I have two different headers for screens smaller than 1070px, causing padding to be added regardless of the presence of "navbar_top". Can med ...

Styling with CSS Variables and Transforming Elements

After conducting thorough research both on this platform and via Google, I have yet to find a solution to my query: "how can CSS variables be utilized in a CSS transform?" Within the HTML header, three CSS variables and their fallback values are declared: ...

What is the best way to set the source of an image using JavaScript

On a recent project, I came across this function in PHP: foreach ($reports["included_reports"] as $index => $report_name ) { if (! in_array( $report_name, $reports["excluded_reports"])) { $optional_reports .= "<div class=\"la ...

Is there a way for me to trigger an error within my Django form?

Currently, I have set up a PHP script on a server that responds with {"available":true} or {"available":false} based on the availability of an email address. The code used for this script is as follows: <?php $servername = "localhost"; $username = "ro ...

What is the process for bringing a function into JavaScript?

I'm currently working on a Discord bot using JS with Node.js, and I've decided to organize my commands by writing each one in a separate file within a "commands" folder. Here's a snippet of my code: in index.js : const help = require("./comm ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

What is the best way to allow users to click a Grid component in order to toggle the state of a

I have a Grid component that is part of a row within the grid container, along with other rows. This particular row consists of a description and a checkbox. How can I set it up so that clicking anywhere on the row will toggle the checkbox on and off? &l ...

Managing user inputs and storing them in separate variables in C#

My previous code successfully handles input in the format "01/01/2017." string monthfrom; string yearfrom; string valfrom = "01/01/2017"; valfrom = valfrom.Replace("/", string.Empty); ...

Tips for correctly sending the response code from a Node.js API

I have a straightforward node-based API that is responsible for parsing JSON data, saving it into a Postgres database, and sending the correct response code (e.g., HTTP 201). Here is an excerpt of my code: router.route('/customer') .post(fu ...

Exploring promise chaining in mongoDB (and mongoose): A guide to effectively utilizing .save() following .then() and gracefully exiting a promise chain upon sending a response

Currently, I have implemented a code snippet for user signup that involves several steps. Initially, I validate the user input to ensure its correctness. Following this, I verify if the user already exists in the system, and if so, I return a response of 4 ...

Combine object attributes to create a new column in a table

Check out this plunker I created. What is the most efficient way to merge the contents of $scope.blacklist into $scope.friends when ng-click="showColumn('Blacklist');" is triggered, and also add a new column named Coming to the table. Ng-App &am ...

Is there a way to dynamically adjust the position of a canvas element using CSS?

After coding in React, I am facing an issue with the canvas element. When I use a mouse-click to adjust the position and change 3 style properties, everything seems fine until I refresh the page. Upon refreshing, I retrieve the canvas elements' positi ...

Saving a Coordinated Universal Time and showcasing it in the corresponding local timezone

In my upcoming MVC4 application that will have a global audience, one of the features involves recording the date and time when a transaction is added or modified. Since I am storing the transaction datetime in UTC format, what would be the most effective ...

Error handling in Spring MVC's @ResponseBody annotation

I am encountering an issue with passing an entity GroupStudent object from my Spring Controller to a JSP page using an ajax function. When attempting to pass the GroupStudent object using @ResponseBody, I consistently receive an error in the browser: Error ...

How can I sort child divs based on a data attribute containing recent date time using jQuery?

Organizing sections by their respective category names and reordering child div elements based on the data attribute, sorted in descending order from most recent to oldest published date. However, encountering issues with the function reArrangeVideosByRece ...