write me a function in react that will accept rows array, each row has a percent value.…
- User
write me a function in react that will accept rows array, each row has a percent value. I need my function to check if the row is selected and if it is selected calculate mean percent of selected rows. Function needs to return that number
- Assistant
Here's a function in React that will achieve the desired functionality:
import React from 'react'; const calculateMeanPercent = (rows) => { let selectedRows = rows.filter(row => row.selected); if(selectedRows.length === 0) { return 0; } let sum = selectedRows.reduce((total, row) => total + row.percent, 0); return sum / selectedRows.length; } // Example usage const rows = [ { id: 1, percent: 50, selected: true }, { id: 2, percent: 75, selected: true }, { id: 3, percent: 60, selected: false }, { id: 4, percent: 90, selected: true } ]; const App = () => { const meanPercent = calculateMeanPercent(rows); return ( <div> <p>Mean Percent of Selected Rows: {meanPercent}%</p> </div> ); } export default App;In this example, the
calculateMeanPercentfunction takes an array ofrowsas its argument. It filters the rows array based on theselectedproperty and then calculates the mean percent by summing up the percent values of selected rows and dividing it by the number of selected rows. Finally, it returns the mean percent value.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.