javascript reduce to the specified array

Having an array called List that consists of objects with id, name, and grade properties. I'm working on designing a dropdown menu in React where the name is displayed on the left and the corresponding grades are displayed in the dropdown on the right. However, I'm facing an issue where only grades belonging to a specific name should be shown in the dropdown.

const List = [
{id:1, name:"jack", grade:'98'},
{id:2, name:"jack", grade:'96'},
{id:3, name:"jack", grade:'80'},
{id:4, name:"jack", grade:'76'},
{id:5, name:"jack", grade:'78'},
{id:6, name:"marry", grade:'90'},
{id:7, name:"marry", grade:'91'},
{id:8, name:"marry", grade:'96'},
{id:9, name:"marry", grade:'95'},
{id:10, name:"marry", grade:'82'},
{id:11, name:"paul", grade:'87'},
{id:12, name:"paul", grade:'98'},
{id:13, name:"paul", grade:'95'},
{id:14, name:"paul", grade:'93'},
{id:15, name:"paul", grade:'75'},
]

To tackle this problem, I need to create new arrays containing the grades for each individual name. For example, when the name is jack, the grade array should be [98, 96, 80, 76, 78]. Similarly, when the name is marry, the grade array should be [90, 91, 96, 95, 82]. I've attempted using the .map() method but need guidance on how to properly iterate through each name to achieve this behavior.

Answer №1

To retrieve a list of objects and their corresponding grades, utilize the filter method to extract the objects and then use map to isolate the grades as shown below:

const List = [
{id:1, name:"jack", grade:'98'},
{id:2, name:"jack", grade:'96'},
{id:3, name:"jack", grade:'80'},
{id:4, name:"jack", grade:'76'},
{id:5, name:"jack", grade:'78'},
{id:6, name:"marry", grade:'90'},
{id:7, name:"marry", grade:'91'},
{id:8, name:"marry", grade:'96'},
{id:9, name:"marry", grade:'95'},
{id:10, name:"marry", grade:'82'},
{id:11, name:"paul", grade:'87'},
{id:12, name:"paul", grade:'98'},
{id:13, name:"paul", grade:'95'},
{id:14, name:"paul", grade:'93'},
{id:15, name:"paul", grade:'75'},
];

const getGrade = name => List.filter(val => val.name === name).map(info => info.grade);

console.log('jack',getGrade('jack'));
console.log('paul',getGrade('paul'));

Answer №2

const StudentList = [
{id:1, name:"Alice", grade:'95'},
{id:2, name:"Alice", grade:'98'},
{id:3, name:"Alice", grade:'85'},
{id:4, name:"Alice", grade:'90'},
{id:5, name:"Alice", grade:'88'},
{id:6, name:"Bob", grade:'92'},
{id:7, name:"Bob", grade:'93'},
{id:8, name:"Bob", grade:'96'},
{id:9, name:"Bob", grade:'94'},
{id:10, name:"Bob", grade:'87'},
{id:11, name:"Charlie", grade:'89'},
{id:12, name:"Charlie", grade:'96'},
{id:13, name:"Charlie", grade:'93'},
{id:14, name:"Charlie", grade:'91'},
{id:15, name:"Charlie", grade:'83'},
]
const gradesByStudentName = {};
StudentList.map(student => {
    if(!gradesByStudentName[student.name]) {
        gradesByStudentName[student.name] = [];
    }
    gradesByStudentName[student.name].push(student.grade);
})
console.log(gradesByStudentName);

Answer №3

It seems like you're looking to condense the array, not just extract grades for each individual. Here's one way to achieve that:

const StudentData = [
{id:1, name:"jack", grade:'98'},
{id:2, name:"jack", grade:'96'},
{id:3, name:"jack", grade:'80'},
{id:4, name:"jack", grade:'76'},
{id:5, name:"jack", grade:'78'},
{id:6, name:"marry", grade:'90'},
{id:7, name:"marry", grade:'91'},
{id:8, name:"marry", grade:'96'},
{id:9, name:"marry", grade:'95'},
{id:10, name:"marry", grade:'82'},
{id:11, name:"paul", grade:'87'},
{id:12, name:"paul", grade:'98'},
{id:13, name:"paul", grade:'95'},
{id:14, name:"paul", grade:'93'},
{id:15, name:"paul", grade:'75'},
];
const condensedList = StudentData.reduce((accumulated, current) => {
  const found = accumulated.find(item => item.name === current.name);
  if (found) found.grade.push(current.grade);
  else {
    accumulated.push({
      name: current.name,
      grade: [current.grade],
    });
  }
  return accumulated;
}, []);


console.log(condensedList);
// [ { name: 'jack', grade: [ '98', '96', '80', '76', '78' ] },
// { name: 'marry', grade: [ '90', '91', '96', '95', '82' ] },
// { name: 'paul', grade: [ '87', '98', '95', '93', '75' ] } ]

Answer №4

Construct an object where the keys represent names and the values are a collection of grades by utilizing the forEach method for efficient data aggregation.

const StudentList = [
{id:1, name:"jack", grade:'98'},
{id:2, name:"jack", grade:'96'},
{id:3, name:"jack", grade:'80'},
{id:4, name:"jack", grade:'76'},
{id:5, name:"jack", grade:'78'},
{id:6, name:"marry", grade:'90'},
{id:7, name:"marry", grade:'91'},
{id:8, name:"marry", grade:'96'},
{id:9, name:"marry", grade:'95'},
{id:10, name:"marry", grade:'82'},
{id:11, name:"paul", grade:'87'},
{id:12, name:"paul", grade:'98'},
{id:13, name:"paul", grade:'95'},
{id:14, name:"paul", grade:'93'},
{id:15, name:"paul", grade:'75'},
]

const studentGrades = {};
StudentList.forEach(
  ({ name, grade }) => (studentGrades[name] = (studentGrades[name] ?? []).concat([grade]))
);

console.log(studentGrades["jack"]);
console.log(studentGrades["paul"]);

Answer №5

To start, you can create an array to store the names of all students. Then, by using the map function, generate an array of objects that will provide the desired result.

let studentList = [
{id:1, name:"jack", grade:'98'},
{id:2, name:"jack", grade:'96'},
{id:3, name:"jack", grade:'80'},
{id:4, name:"jack", grade:'76'},
{id:5, name:"jack", grade:'78'},
{id:6, name:"marry", grade:'90'},
{id:7, name:"marry", grade:'91'},
{id:8, name:"marry", grade:'96'},
{id:9, name:"marry", grade:'95'},
{id:10, name:"marry", grade:'82'},
{id:11, name:"paul", grade:'87'},
{id:12, name:"paul", grade:'98'},
{id:13, name:"paul", grade:'95'},
{id:14, name:"paul", grade:'93'},
{id:15, name:"paul", grade:'75'},
]

let students = [];
let grades = [];
for(let record of studentList) {
    if(!students.includes(record.name)) students.push(record.name);
}
console.log(students);
students.map(student => {
    let gradeList = [], studentObj={};
    studentList.map(data => {        
        if(data.name === student) gradeList.push(data.grade);
    })
    studentObj.name = student;
    studentObj.grades = gradeList;
    grades.push(studentObj);
})
console.log(grades);

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 of parsing a Java property file in AngularJS?

Is it possible to access a properties file from an AngularJS application that is located outside of the web server? For example, in Java we can access a property file deployed separately from the project. Is there a way to achieve this in AngularJS? I at ...

Is it possible to modify a line after it has been printed using System.out.println()?

After spending a significant amount of time coding, I have come to understand that once a line is outputted to System.out.println in Java, it cannot be changed. The reason for my inquiry stems from some perplexing results produced by my program. This part ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

Is there a way to create a personalized right-click context menu that displays dual links to a specific page on my website?

I want to create a custom right-click menu for users with two choices: Contact (link: Contact Us) Support (link: Support Page) <html> <head> <script type="text/javascript> if (document.addEventListener) { // IE >= 9;other br ...

What could be the reason for my jQuery focusout (or blur) event failing to trigger?

On the jsfiddle link provided, the HTML code at the end section looks like this: <input type="text" id="BLAboxPaymentAmount" value="2"> </br> <input type="text" id="BLAboxSection5Total" value="3"> Below that is the jQuery code snippet: ...

Clean up unnecessary arrays within PHP arrays

My mind is drawing a blank right now, I have an array that appears as follows: Array ( [0] => Array ( 'fruit' => 'orange', ) [1] => Array ( 'fruit' => 'apple', ) ) and it needs to be transformed into ...

mapping through an array results in promises that are not yet resolved

I am working with an array of values and I want to return an object that uses each value in a promise. This is the code I have: const exampleArray = serieses.map(async x => { const seriesId = await getSeriesIDFromName(x); return { part_id: pa ...

Typescript mapping data structure

Currently, I am facing the challenge of mapping complex models. My data consists of an array of Carts with attributes such as id and name. In addition, there is a dictionary where each key represents a type and its corresponding value includes different p ...

SyntaxError: VM3419:1 - Unexpected token "<" was not caught

I'm exploring AJAX techniques in a demo project where I retrieve data from the server using AJAX methods. However, I encountered the following error: " Uncaught SyntaxError: Unexpected token< xhr.onreadystatechange @main.js" JS: (function ...

validating price ranges with the use of javascript or jquery

<!DOCTYPE html> <html lang="en"> <head> <title>My Page Title</title> </head> <body> <form method="post" action="process-form.php"> Price Range: From <input type="text" id="price-from"> ...

Python program to iterate through a matrix and verify the presence of each value in a vector

For my analysis, I have created a vector called possibleGrades containing the values [-3, 0, 2, 4, 7, 10, 12]. Now, I need to identify which cells in a given matrix do not correspond to any of these grades from the vector: [[ 7. 7. 4. ] [12. 10. 10 ...

What is the best way to showcase the output of a Perl script on a webpage

I recently came across a resource discussing the process of executing a perl script from a webpage. What is the best way to run a perl script from a webpage? However, I am facing a situation where the script I have takes more than 30 seconds to run and d ...

"Can you help me understand how to establish a character limit for the MUI autocomplete

Hey everyone, I have successfully created an auto-complete feature using Material UI and an API. Now, I am facing a challenge where I need to limit the suggestions returned by the autocomplete to only show matches when the user types at least 3 letters. Ca ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...

Refining keys within an array of objects

If I have an array of objects retrieved from a Node Repository like this: data = [ { title: "JavaScript Basics", author: "John Smith", year: 2020 }, { title: "Node.js Essentials", ...

How to send an array as an argument in a jQuery function

I'm attempting to pass an array as an argument in a function Check out the --> updated fiddle <-- After running some tests, it appears that the function is interpreting the argument as a string instead of an array. How can I successfully pass ...

"Troubleshooting CSS styling in React material-ui when using withStyles from an external

After reviewing this specific question, I still couldn't figure out how to make it work. The main goal is to keep the styles separate from the component file for a more organized setup. Everything runs smoothly without incorporating a theme. I atte ...

Retrieving parameters from the URL in Angular

I'm facing an issue with my app. I am currently using a factory to manage data for two controllers. When I click on a link that redirects me to another view with a specific URL, I want to reuse the last tag in the URL by slicing it like this: window. ...

"Exploring the possibilities of combining AngularJS with PHP to manipulate

Recently, I started diving into AngularJS and encountered a situation where I needed to fetch data from a database as an array using a foreach function. Here is a snippet of the code I used: <ul> <?php foreach($Items as $Item):?> ...

Step-by-step guide to adding products to your Supabase shopping cart

I have managed to insert a row into the "order" table with user information. Now, I want to individually add item details to a separate table named "order_storeItems" to create a relationship between the order and storeItems tables. I attempted using Pro ...