Is it possible to iterate over an array and invoke a function at the same time?

const students = ['John', 'Mark'];
const weight = [92, 85]
const height = [1.88, 1.76]

function yourBodyMass(name, funct, mass, height) {
  console.log(`${name}, your body mass index is ${funct(mass, height)}.`)
}

function calculateBMI(mass, height) {
 const BMI = mass / height ** 2;
  return BMI;
}

function loopStudents() {
 for (let i of students) {
  return yourBodyMass(students[i], calculateBMI)
 }
}

Is it possible to loop through the students array without having to declare the yourBodyMass function repeatedly? Please let me know.

Answer №1

Your code seems a bit messy. Here is a suggested improvement:

const students = ['John', 'Mark'];
const weight = [92, 85]
const height = [1.88, 1.76]

function calculateBodyMassIndex(studentName, func, mass, height) {
    console.log(studentName + ' your BMI is ' + func(mass, height));
}

function getBMI(mass, height) {
    const BMI = mass / height ** 2;
    return BMI;
}

function loopData() {
    for (var i = 0; i < students.length; i += 1) {
        calculateBodyMassIndex(students[i], getBMI, weight[i], height[i]);
    }
}

If it were me, I would simplify the code by removing the calculateBodyMassIndex function, like so:

const students = ['John', 'Mark'];
const weight = [92, 85]
const height = [1.88, 1.76]

function calculateBMI(weight, height) {
    return weight / height ** 2;
}

function loopData() {
    for (var i = 0; i < students.length; i += 1) {
        let BMI = calculateBMI(weight[i], height[i]);
        console.log(students[i] + ' your BMI is ' + BMI);
    }
}

Note that I changed the function name from bodyMass to calculateBMI for better clarity and cleaner code.

Answer №2

Expanding on the response from @vanowm, it is advisable to organize a collection of student data with attributes like name, weight, and height into individual student objects or instances within an array structure. This can be achieved in a straightforward manner:

const students = [
   { name: 'John', weight: 92, height: 1.88},
   { name: 'Mark', weight: 85, height: 1.76},
];

Subsequently, one can iterate over the array using a forEach loop:

students.forEach(student => {
   yourBodyMass(student.name, bodyMass, student.weight, student.height)
});

const students = [{
  name: 'John',
  weight: 92,
  height: 1.88
}, {
  name: 'Mark',
  weight: 85,
  height: 1.76
}];

function yourBodyMass(name, funct, mass, height) {
  console.log(`${name} your BMI is ${funct(mass, height)}.`)
}

function bodyMass(mass, height) {
  const BMI = mass / height ** 2;
  return BMI;
}

students.forEach((student) => {
      yourBodyMass(student.name, bodyMass, student.weight, student.height)
    })

Answer №3

Here are four issues identified in your code:

  1. The return statement will stop the loop and exit the function after processing the first item in the array
  2. The function yourBodymass() should actually be written as youBodyMass() with a capital letter (note the missing capital letter)
  3. When using of in the for loop, the variable i will represent the value from the array, not the index
  4. You have failed to pass the necessary weight and height data into the yourBodyMass function

Please attempt to address these issues independently without referring to the solution.

const students = ['John', 'Mark'];
const weight = [92, 85]
const height = [1.88, 1.76]

function yourBodyMass(name, funct, mass, height) {
  console.log(`${name} your BMI is ${funct(mass, height)}.`)
}

function bodyMass(mass, height) {
 const BMI = mass / height ** 2;
  return BMI;
}

function loopData() {
 for (let i = 0; i < students.length; i++) {
  yourBodyMass(students[i], bodyMass, weight[i], height[i])
 }
}

loopData()

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

JavaScript: unable to locate information within JSON reply

Looking to develop a Twitter bot utilizing the Twitter and Spotify APIs. Making progress, but encountered an issue I can't tackle alone: Seeking the artist and song name of the top 1 track from the top 50 Spotify songs. Upon sending a request to the ...

Transitioning from webpack to vite with Vue.js for a Chrome extension development project

I am currently developing a Chrome extension using Vue.js. I have a project ready to start with, but it is set up with webpack. Within webpack, I have multiple entry points that result in the generation of HTML files and others with JavaScript only. Whil ...

Are these two sections of my code distinctive in functionality? Do they both address potential errors in the same manner?

After receiving some helpful suggestions on my code from a user on stack overflow, I decided to revisit and make improvements. However, I am now questioning whether the changes I made handle errors in the same way as the original code. This is my initial ...

Maintaining a security token across multiple requests

A prototype application is being developed with the following features: An HTML website integrated with knockoutjs Communication with Web API services using jQuery/Ajax The goal is to restrict access to services only to authorized users. Security measur ...

Is it possible for the controller of a modal window to have access to functions within the parent controller

If you were to launch a modal window using $modal.open from an angular directive, would the modal window be able to access functions defined within the parent directive? Below is the code for the directive controller: function parentFunction() { re ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

Difficulty in defining the header while using the submit hook in Remix 1.15

When I utilize the useSubmit hook to send a POST request, it appears that the header I specify is not being taken into account. Below is the code snippet for my submit function: submit('/dashboard/', { method: 'post', heade ...

Leveraging Vue 2.0 and webpack to integrate components from an npm package

As I venture into setting up a project with webpack and Vue 2.0, I encountered a slight hiccup when trying to incorporate components from npm packages (such as vue-parallax) into my project. Upon installing the package, everything seems to be in place, bu ...

What is the best way to incorporate images from an external module into my React project?

Is there a way to include images from an external module (npm install external-module) in my project's public assets? The images are located in the directory path myProject/node_modules/external-module/dist/img. ...

What is the best way to choose dropdown values by utilizing various button IDs?

I have four different vacation destinations and four buttons. I want to automatically select each destination separately when the corresponding button is clicked. <select class="aa" required="" name="f1990" {input.multiple}="" {input.size}="" id="f19 ...

Manipulating the InnerHTML content of a total of 144 individual cells

I am currently developing a tile-based game using tables. Each td cell contains the following code: <td> <div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo ...

Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon. @Directive({ selector: '[appDatepicker]' }) export class DatepickerDirective implements DoCheck{ constru ...

React DataGrid fails to refresh when state changes

Currently, I am in the process of developing a link tree using the Datagrid Component provided by MaterialUI. While data can be successfully displayed, I encounter an issue when attempting to add a new entry. The problem lies in the fact that despite cha ...

Exploring Iconography in Amcharts

Is there a simple way to include images/icons within a chart using x and y coordinates? I'm new to javascript and amcharts (am4charts) so any assistance would be greatly appreciated! I've searched for solutions on stackoverflow, like this one o ...

Combine rows with the same value in the first column of an HTML table

My HTML table has dynamic content, and I need to merge rows in the first column only if their values are identical. You can see an image of the table here. Specifically, if the values in the first column match, those rows should be merged together while le ...

What is the best way to change routes within my React application?

I am currently facing a challenge with the Routes in my work's web application. The existing method of accessing routes involves manually typing in the extended path in the browser, which is not ideal. I want to enhance this by adding new routes that ...

The AJAX function failed to trigger another JavaScript function after successfully completing its task

Trying to figure out how to execute a function after successful AJAX post request. The function I want to call is: function col() { var $container = $(".post-users-body"); $container.imagesLoaded(function() { $container.masonr ...

Error encountered: No geographic indices found for executing a geoNear operation with Mongoose

Initially, I had divided the schemas but later nested them inside my overall document. Despite adding indexes and removing coordinates from location, there seems to be an issue with the nested points. Upon running get Indexes, it shows that there is an i ...

Issue with IE preventing Selenium from triggering Onchange event and causing page to fail to Postback

I am currently working on a web application where selecting an item from one drop-down list triggers the loading of another. However, when using Selenium to automate this process, I have encountered an issue where the page post back is prevented and the se ...

Include the await keyword within the .then block

I'm trying to execute an await after receiving a response in the .then callback of my code: const info = new getInfo(this.fetchDetails); info .retrieve() .then((res) => { const details = this.getLatestInfo(res, 'John'); }) .ca ...