My goal is filter data based on a user's selection in a drop-down menu.
SET UP
I have an array of objects named employees. First, I sort by the salary attribute, then using another function manipulateData(), I filter by role attribute (which the user selects via a drop-down menu).
(notice in the HTML file that the manipulateData() function is called onchange)
Here is my code:
JavaScript:
let employees = [
{
id : 1,
name : 'John Smith',
role : 'Sales',
salary : 100000
},
{
id : 2,
name : 'Mary Jones',
role : 'Finance',
salary : 78000,
},
{
id : 3,
name : 'Philip Lee',
role : 'Finance',
salary : 160000,
},
{
id : 4,
name : 'Susan Williams',
role : 'Sales',
salary : 225000,
},
{
id : 5,
name : 'Jason Alexander',
role : 'Finance',
salary : 90000,
},
{
id : 6,
name : 'Derek Sanders',
role : 'Sales',
salary : 140000,
}
]
// #########################################
function filterData() {
let allData = employees;
let selectBox = document.getElementById("employee-role");
let selectedValue = selectBox.options[selectBox.selectedIndex].value;
// SORT SALARIES DESCENDING
allData.sort(function (a, b) {
return b.salary - a.salary;
})
console.log('Sorted Data', allData);
// *** Here is where I'd like to invoke the dataManipulation() function to filter on only the user-selected roles
// LIMIT TO ONLY 2 RECORDS
let filteredData = allData.filter( (value, index) => {
return (index < 2);
});
// RENDER THE CHART
//renderChart(filteredData);
}
function manipulateData(filteredData) {
return filteredData.filter(e => e.role === selectedValue)
}
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<title>Example</title>
</head>
<body>
<div class="container-fluid">
<!-- header -->
<div class="row justify-content-center">
<div class="align-self-center">
<h1>Example</h1>
</div>
</div>
<!-- drop down menu -->
<div class="row justify-content-center">
<div class="align-self-center">
<div class="user-control">
<div class="form-group">
<select id="employee-role" class="form-control" onchange="manipulateData()">
<option value="All">All Roles</option>
<option value="Sales">Sales</option>
<option value="Finance">Finance</option>
</select>
</div>
</div>
</div>
</div>
<!-- container of bar chart -->
<div id="chart-area"></div>
</div>
</body>
</html>
Question: before I reduce the size of the data set to 2 records, how would I incorporate the manipulateData() function to grab only the role selected by the user via the drop-down menu?
Thanks! (JavaScript newbie here)