Transforming a string into an array of objects into an array of numerical values

Can anyone assist me in extracting an array of numbers from an array of objects with string values as properties? Below is an example of the array:

  scores = [
               {
                  maxScore:"100"
                  obtainedScore:"79"
                  passed:"pass"
                  subject:"Maths"
               },
               {
                  maxScore:"100"
                  obtainedScore:"73"
                  passed:"pass"
                  subject:"Science"
               },
               {
                  maxScore:"100"
                  obtainedScore:"82"
                  passed:"pass"
                  subject:"English"
               }
           ]

I would like to extract obtainedScore and maxScore from these objects and store them in two different arrays.

Here is what I attempted:

for (var  i =0 ; i < score.length; i++)
{ 
   var marks[i] = parseInt(score[i].obtainedScore) ;
} 

However, this resulted in returning NaN.

Answer №1

  1. ANSWER OBTAINED FROM YOUR TRIAL:

        var scores = [{
          maxScore: "100",
          obtainedScore: "79",
          passed: "pass",
          subject: "Maths"
        }, {
          maxScore: "100",
          obtainedScore: "73",
          passed: "pass",
          subject: "Science"
        }, {
          maxScore: "100",
          obtainedScore: "82",
          passed: "pass",
          subject: "English"
        }]
        var marks = [];
        for (var i = 0; i < scores.length; i++) {
          marks[i] = parseInt(scores[i].obtainedScore, 10);
        }
        console.log(marks)

  2. MY SOLUTION (before your modification)

var scores = [{
      maxScore: "100",
      obtainedScore: "79",
      passed: "pass",
      subject: "Maths"
    }, {
      maxScore: "100",
      obtainedScore: "73",
      passed: "pass",
      subject: "Science"
    }, {
      maxScore: "100",
      obtainedScore: "82",
      passed: "pass",
      subject: "English"
    }]

    function decoupler(arr, prop) {
      return arr.map(function(item, index) {
        return parseInt(item[prop], 10);
      });
    }
    var arr1 = decoupler(scores, "maxScore");
    var arr2 = decoupler(scores, "obtainedScore");

    console.log(arr1);
    console.log(arr2);

Update: Radix parameter added for parseInt() following the advice of comment by jfriend00.

Answer №2

Have you considered projecting a mapping?

const topResults = results.map(result => parseInt(result.topScore, 10))
const achievedResults = results.map(result => parseInt(result.achievedScore, 10))

Answer №3

While I may not have a complete understanding of your desired outcome, here is a solution:

I would like to extract the obtainedScore and maxScore values from these objects and store them in two separate arrays.

let arrObtainedScores = [],
        arrMaxScores = [];

    scores.forEach(item => {
        arrObtainedScores.push(!isNaN(parseInt(item.obtainedScore)) ? parseInt(item.obtainedScore) : 0);
        arrMaxScores.push(!isNaN(parseInt(item.maxScore)) ? parseInt(item.maxScore) : 0);
    });

This code snippet generates two arrays: arrObtainedScores which contains each obtained score value individually, and arrMaxScores which holds an array of the maximum scores.

By utilizing the forEach function, we iterate through the array and assign the values to their respective arrays. Importantly, we validate that the values are valid integers before pushing them.

Answer №4

results = [
               {
                  topGrade:"A",
                  score:"87",
                  status:"pass",
                  subject:"History"
               },
               {
                  topGrade:"B",
                  score:"65",
                  status:"fail",
                  subject:"Geography"
               },
               {
                  topGrade:"A",
                  score:"92",
                  status:"pass",
                  subject:"Literature"
               }
           ];
           topGradeArray = [];
           scoreArray = [];

           for (var j = results.length - 1; j >= 0; j--) {
           topGradeArray.push(Number(results[j].topGrade));
           scoreArray.push(Number(results[j].score));
           }

           console.log(topGradeArray);
           console.log(scoreArray);

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

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

Send back Complex data type to display using AJAX

My Objective I am dealing with a complex type generated by EF from a stored procedure. This type returns a list of GetAvailableRooms_Results. I want the user to choose two dates and then get a list of available rooms (complex type) returned by the stored ...

Unable to locate a compatible version for require-from-string with the specified version range of ^1.1.0

Needed Packages for npm Project: "dependencies": { "angular-chart.js": "1.1.0", "angular-cookies": "1.5.7", "angular-ui-bootstrap": "2.4.0", "angular-ui-grid": "4.0.5", "checklist-model": "0.10.0", "json-schema": "0.2.2" } Howev ...

Deleting an element from an array in JavaScript

I am working with a JavaScript array that I need to store in local storage. var myArray; myArray = [1,2,3,4,5]; localStorage.setItem('myArray', JSON.stringify(myArray)); The above code snippet sets the values of the 'myArray' ...

What could be the reason for request.json in bottle coming back as None?

I am currently facing an issue with my bottle web server and jQuery when trying to send ajax requests using json. I am uncertain whether the problem lies in the sending or receiving end. Here is a snippet of my code: server.py @route("/jsontest", method= ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

How to Customize the Size and Color of secureTextEntry Inputs in React Native

When it comes to styling a password input like the one below: <TextInput name="Password" type="password" mode="outline" secureTextEntry={true} style={styles.inputStyle} autoCapitalize="none" autoFocus={true} /> I also ap ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

Json-powered Android Login Interface

Hi there! I'm new to Android development and could really use some guidance. So, I have a JSON object that looks something like this: { "Id": 1, "Name": "user", "userId": 4, "active": true, "ProfileId": 1, "Tema": "green ...

The change in $stateparams is not being reflected in the services, even when it is updated outside the factory

var routerApp = angular.module('routerApp', ['ui.router','ngResource']); routerApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider // HOME STATES AND NESTED VIEWS .state('partyDeta ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...

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 ...

Error related to JsonObjectRequest and RequestQueue

SOLUTION: I discovered that the issue lied within the context, and wanted to share in case others encounter the same problem. While working on my android app, I attempted to make a request using JsonObjectRequest and RequestQueue with Volley lib, but enco ...

Parsing through an extensive JSON array to locate a particular item

I have a massive JSON file with the top-level structure being an array, filled with numerous subarrays like: [ [], [], [], ... [] ] Each subarray is small enough to load into memory individually; the file's size mainly comes from the number of suba ...

Is it possible to ban a user who is not a member of the current guild using Discord.js library?

Currently, I am developing a bot with moderation capabilities and have encountered a challenge in finding a method to ban a user other than using member.ban(). While this function works effectively for users who are currently in the guild, it fails to wo ...

I am looking to showcase the JSON output on a ReactJS interface

Here is the output of my JSON data I am using the Map function in ReactJS to display elements from a JSON array. I have attempted the code below and encountered an error stating "Cannot read property '_currentElement' of null." Can someone pleas ...

Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or ...

Using Angular JS to redirect in an Express JS application

When using AngularJS, I make an http get request like this: $http.get('/api/users?id='+userID) If the request is unauthorized, I redirect with a status code from ExpressJS like this: res.status(401).location('/login').end(); But for ...

Ways to retrieve the page name where the script originates from

I have a function that is triggered from three different pages. Each page involves adding an attribute to a specific div. For instance: <div id="posts" page="home"></div> <div id="posts" page="feed"></div> <div id="posts" page= ...

Filtering data within a specific date range on an HTML table using JavaScript

I am attempting to implement a date filtering feature on my HTML table. Users should be able to input two dates (From and To) and the data in the "Date Column" of the table will be filtered accordingly. The inputs on the page are: <input type="date" i ...