Struggling to create the passingGrades function in Javascript, which aims to eliminate any grades below 70 from an array but unfortunately encountering issues

There seems to be an issue with the code snippet provided below. I'm having trouble identifying the problem and would appreciate any assistance.

var scores = [];

var passingScores = function(scores) {

  for (i=0; i < scores.length; i++){

    console.log(scores.filter(function(scores[i]) {

      return scores[i] >= 70;
    }));
  }
};


passingScores([63, 75, 39, 88, 94, 100, 24]);                        

Answer №1

To obtain the filtered array, simply return the result created by utilizing the filter method.

Note: Avoid using a global variable that shares the same name as a local variable!

const passingScores = function(scores) {
  return scores.filter((score) => score >= 70);
};
console.log(passingScores([63, 75, 39, 88, 94, 100, 24]));

Answer №2

When it comes to working with arrays, leveraging methods like filter and map can simplify the process by automatically looping through each item in the array and returning a new array based on certain conditions. This eliminates the need for manual iteration using a for loop.

Instead of writing:
for(i = 0; i < grades.length; i++) {
 for(i = 0; i < grades.length; i++) {
  if(grades[i] > 70) {
   ...
  }
 }
}

We can simply achieve the same result by filtering the grades array directly and returning only the elements that meet our condition. In this case, we can just return the result of grades.filter.

It's important to note that the function passed into .filter will be executed on each item in the array. So instead of referencing each item using grades[i], you can use a more descriptive variable like grade to make your code clearer.

In essence, we are telling the array to filter itself based on a specific condition (in this case, grades greater than or equal to 70), and return a new array with only the filtered items.

var passingGrades = function(grades) {
return grades.filter(function(grade) {
      return grade >= 70;
    });
}


console.log( passingGrades([63, 75, 39, 88, 94, 100, 24]) );      

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

Properly storing information in the mongoDB

Having trouble saving data in my Angular application correctly. Here is a snippet of my API code: .post('/type/add', function(req, res){ var type = new NewType({ type: req.body.type, subtype: req.body.subtype, }); type.save ...

Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure: "topic_list": { "topics": [ { "id": 9148, "title": "A", "views": 12 }, { "id": 3228, ...

What is the best way to navigate to a different page, such as Google, using Node.js?

I need to retrieve a number to store in a short variable, and then search the database for a corresponding shortUrl associated with that number. If a match is found, I want the response to be the full URL, such as www.google.com. For example, if a user ty ...

Transform the array of objects into the desired layout

I have a list containing various campus data. let campuses = [ { "Id": 1, "Name": "North Campus", "OptId": 1, "OptName": "Religious Reasons", "mapp ...

Decoding an array in JSON format from PHP

Hey there! Currently, I am working with an associative array in my PHP file, which I convert into a JSON object and pass to my JavaScript file. My goal is to loop through this array and identify the item with a matching key. Here's what I have done so ...

The URL http://localhost:3001/users/signup returned a 404 error, indicating that the page was

Hello, I've been working on setting up my user routes using Sequelize for MySQL. However, when I try to test my requests by sending them to http://localhost:3001 via Postman, I'm receiving a 404 (Not Found) error for http://localhost:3001/users/s ...

Count up with HTML like a progressive jackpot's increasing value

I am interested in developing a progressive jackpot feature similar to the sample image provided. I would like the numbers to loop periodically. Can anyone advise me on how to achieve this effect? Any suggestions or examples, preferably using JavaScript o ...

To use Material-UI Tooltip, the child title prop must be removed

I am facing an issue while trying to implement the Material-UI Tooltip component on a component that already has the title property. I need to use the child with the title prop, but I'm unsure if it's possible to combine both or if I should look ...

What could be the reason for the delay in the JavaScript number generator?

I have limited knowledge of Javascript, so I modified this code by forking a Pen. Despite searching for similar posts, none seemed to address the issue with lag that I am experiencing. The delay occurs even when there is only one number displayed, making m ...

The top two biggest consecutive arrays

I am currently tackling a problem that bears resemblance to the maximum contiguous sub-array issue. Nevertheless, instead of identifying just one contiguous sub-array, I can pinpoint up to two non-overlapping contiguous subarrays. For instance, in the giv ...

Verify if the SaveAs dialog box is displayed

Can javascript/jquery be used to detect the appearance of a SaveAs dialogue box? I need to know if it's displayed in order to remove a loading gif. Any ideas? ...

Access data from an array within an object using DataTables

Here's a simple question: How do I access an array inside an object using datatables? Object I am trying to access the array "data" : { "success": true, "data": [ { "id": "4", "tienda_id": "5", "tienda_nombre": "sad", ...

Encountering issues with basic login functionality using Node.js and MongoDB - receiving a "Cannot

I'm experiencing some difficulties trying to set up a login for my website. I have a user registered in my database with the email: [email protected] and password 123. The issue arises when I attempt to use the POST method, as it returns the fo ...

What is the best method for displaying 3 items in each row from a mapped response in ReactJS using materialize css grids or react bootstrap grids?

I have been attempting to display three or four response items in a mapped out response on the same row, but I haven't had much success. While I have researched similar questions on Stack Overflow, I couldn't quite figure out how to apply those s ...

I am encountering a JSON parsing error while trying to implement jQuery autocomplete, despite using a local array

I'm attempting to implement the jQuery autocomplete feature on a WordPress website. My ultimate goal is to link the input field to an ajax request that will retrieve data from a database. However, I've encountered an unusual error when trying to ...

Error: Unable to access the currentTime property as it is not defined

Incorporating Videojs into my react application has presented a challenge. I am attempting to set the current time of the videojs player, but keep encountering an error that reads "cannot read property currentTime of undefined". Below is my approach: var ...

Error 404: Postgres and NodeJs API not found (Possible duplicate)

I am new to developing with Node.js and currently working on creating APIs using node, express, and a Postgres database. const {Pool} = require('pg'); //const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/tu ...

Modify the text on a button using vanilla JavaScript

Although it may seem like a simple question, I am struggling to change the text on my button. The code for my button in the web browser console is: <button class="nav-link active" id="coholder-tab" data-toggle="tab" data-t ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Is it possible to alter the css twice through the action of clicking on two individual buttons

One feature I have in my interface allows users to click on the edit button to bring up borders and change the background color of other divs. Once the edit button is pressed, it is replaced by cancel and save buttons. The goal is for the borders and backg ...