Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below:

+------+---------+----+----+----+----+-------+----------+
| Year | Subject | A  | B  | C  | F  | Total | PassRate |
+------+---------+----+----+----+----+-------+----------+
| 2015 | Maths   | 12 | 20 | 10 |  5 |    47 |       80 |
| 2015 | Sinhala | 18 | 14 |  5 | 10 |    47 |       75 |
| 2016 | Maths   | 25 | 15 |  4 |  8 |    52 |       25 |
| 2016 | Sinhala | 20 | 12 |  2 | 18 |    52 |       60 |
+------+---------+----+----+----+----+-------+----------+

To store this data in a JavaScript array, the following code is used:

var firstArray = [];
firstArray.push(['Year', 'Subject', 'A', 'B', 'C', 'F', 'Total', 'PassRate']); // headers
firstArray.push([2015, 'Maths', 12, 20, 10, 5, 47, 80]); // 1st row
firstArray.push([2015, 'Sinhala', 18, 14, 5, 10, 47, 75]) // 2nd row
console.log(firstArray);

If there is a need to find out how many "B"s are in Maths for the year 2015, one would have to use firstArray[1][3].

This method of accessing data may not be very intuitive. Is there a way to structure the array in a more readable format such as firstArray[2015]['maths'] to easily retrieve information like the number of "B"s in Maths for the year 2015?

Answer №1

It sounds like you're looking for a data structure where each year is associated with different subjects and their corresponding grades:

const gradeBook = {
  '2015': {
    Maths: {
      A: 12, B: 20, C: 10, F: 5, Total: 47, PassRate: 80
    },
    Sinhala: {
      A: 18, B: 14, C: 5, F: 10, Total: 47, PassRate: 75
    },
  },
  '2016': {
    // ...
  }
}
console.log(gradeBook['2015'].Maths);

Answer №2

Ensuring the readability of your code is crucial for its success.

Although there is no definitive path to follow, I can offer some suggestions on how to improve your code.

Firstly, let's talk about naming conventions.

Naming variables can be a challenging task, even for seasoned developers who often find themselves renaming variables multiple times before settling on the right one.

For example, using a variable name like firstArray provides little context as to what the array actually contains.

A more descriptive name such as studentsScoreByYear gives a better indication of the content within the array.

Next, let's address the issue of "magic numbers" and index values.

Using hard-coded integers in your code can make it difficult to remember the purpose of each field or element.

An alternative approach is to utilize hash maps or plain objects in JavaScript, allowing you to assign meaningful names to each field.

If abandoning arrays is not an option, consider using constants to represent specific indexes:

 var MATHS = 1;
 var SCORE_OF_B = 3;

 var studentsScoreByYear= [
    ['Year', 'Subject', 'A', 'B', 'C', 'F', 'Total', 'PassRate'],
    [2015, 'Maths', 12, 20, 10, 5, 47, 80],
    [2015, 'Sinhala', 18, 14, 5, 10, 47, 75]
];

console.log(studentsScoreByYear[MATHS][SCORE_OF_B]);

Remember, there are various approaches to improving code readability - this is just one possibility.

Answer №3

Representing your data in a readable format often requires a list of objects.

When it comes to selecting data:

  • Filter an array using the filter method.
  • Isolate a parameter or alter contents with the map method.
  • Perform arithmetic operations utilizing the reduce method.

var data = [
    { year: 2015, subject: 'Maths', a: 12, b: 20, c: 10, f: 5, total: 47, passrate: 80 },
    { year: 2015, subject: 'Sinhala', a: 18, b: 14, c: 5, f: 10, total: 47, passrate: 75 },
    { year: 2016, subject: 'Maths', a: 25, b: 15, c: 4, f: 8, total: 52, passrate: 25 },
    { year: 2016, subject: 'Sinhala', a: 20, b: 12, c: 2, f: 18, total: 52, passrate: 60 },
];
console.log("Present All:");
console.log(data
    .map(function (row) {
    return [row.year, row.subject, row.a, row.b, row.c, row.f, row.total, row.passrate].join(", ");
})
    .join("\n"));
console.log("Count `B` in `Maths` in 2015");
console.log(data
    .filter(function (row) { return row.year === 2015 && row.subject === "Maths"; })
    .map(function (row) { return row.b; })
    .reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0));

Sidenote

For those keen-eyed individuals, the map and filter calls may seem redundant in the "Present All" example since it could be simplified to:

data.reduce(function (accumulator, row) {
    return accumulator + (row.year === 2015 && row.subject === "Maths" ? row.b : 0);
}, 0);

Although the above code is more concise, the detailed approach using map and filter can provide better insight for anyone learning about handling arrays and objects in JavaScript.

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

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

When attempting to change the text in the textarea by selecting a different option from the dropdown list, the text is not updating

I am facing an issue with three multi-select dropdown lists. When a user selects options from these lists and then presses the submit button, the selected text should display in a textarea. However, if the user manually changes some text in the textarea ...

How can one properly utilize material-ui CSS?

Just starting out with material-ui and react, I'm currently following this palette customization guide from Material-UI. However, when attempting to replicate the example shown, I encountered the error: Cannot read property 'prepareStyles' ...

Combining a 2D array with a 3D array to create a larger 3D array with an expanded third dimension

I am facing a challenge with two arrays in my coding project. Array A represents 3124 models with 5 reference parameters, while array B represents 3124 models, 19 time steps per model, and 12288 temperature field data points per time step. My goal is to a ...

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

String variable representing the name of a React element

As I was reviewing the source code of a React UI library, I stumbled upon an interesting code pattern that I will simplify here: function Test() { let Button = "button"; // ... return <Button>Click me</Button>; } I'm curious about ...

How can you move away from using the url:port scheme with socket.io?

Recently, I've been delving into node.js and socket.io, but I'm struggling to eliminate the need to type "url:port" in the browser. Instead, I want users to simply enter the URL and have everything load up, similar to my work-in-progress single p ...

Creating a pattern for values ranging from 18 to 99, including leading zeros, using regular expressions

Looking for a Regular Expression that matches numbers from 018 to 099, inclusive. The numbers must range between 18 and 99, and include a leading zero for values less than 100. ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

Component template using Knockout.js and RequireJS for HTML widgets

Trying to implement the widget example for knockout from here. Unfortunately, I am having issues loading the template from an external HTML file using requirejs. ko.components.register('like-or-dislike', { template: { require: &apos ...

What exactly is the purpose of the QueryString function and how does it work

I recently took on the role of editor for a website that I did not create. One of the webpages contains a map feature, and I've been tasked with changing how the map loads initially on the webpage. As I review the JavaScript code, I'm unsure if ...

waiting to display information until it is necessary

I am currently working on optimizing my website for improved loading speed and responsiveness. Users can scroll through up to 4k images, apply filters, and sort them based on their preferences. Below is the code snippet for my filtering function: function ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Unexpected Error: The axiosCookieJarSupport function is throwing a TypeError, functioning properly in Node.JS but not in .vue pages. What could

Struggling with a function that authenticates on a website, it runs smoothly in a basic node.js script but fails when executed from a .vue page within the NuxtJS framework. The error message received when running in the .vue page is TypeError: axiosCookie ...

Can JavaScript event listeners be compelled to trigger in a specific sequence?

Is there a way in JavaScript to receive notification or execute a callback function once an event has completed its propagation? Put differently, is it possible to 'prioritize' an event and ensure that it gets triggered after all other event lis ...

Having trouble changing the Font Awesome icon on click?

I'm struggling to figure out why I can't change a font awesome icon using a toggle. I've tried various solutions but nothing seems to be working. Any insights on what might be causing this issue? (HTML) <span class="toggle-icon" ...

When attempting to import my JSX file into page.js, I continue to encounter the error "module not found." How can I troubleshoot and resolve this issue in Visual Studio Code

I recently created a new file called mysec.jsx in the components folder of src. I then used the export function to properly export it. However, when I tried to import this file in page.js using the import function, I encountered an error message that said: ...

What is the best way to retrieve the content from the MongoDB Document in my GET request?

I encountered an issue while attempting to access the Question field within the JSON document body stored in a MongoDB database. Upon executing the GET request, the result displayed as follows: { "_readableState": { "objectMode": true, "highWaterM ...