如何根据用户选择过滤我的平均功能?

时间:2018-04-28 04:36:24

标签: javascript user-controls

我正在尝试根据用户选择过滤我的平均功能 我正在使用JavaScript,我的所有数据都在JSON文件中

我的平均功能是:

function loadJSONishDataOften() { //function for the average often button 
var m = JSON.parse(data);
var myObjectArray = [];
for (var i = 0; i < m.length; i++) {
    myObjectArray[i] = new MediaClass (m[i].favorite, m[i].day, m[i].often, m[i].lon, m[i].device, m[i].advert );
}   
document.getElementById("demo2").innerHTML = "On average people go on social media: " + " " + calulateAverageOften(myObjectArray) + " times per day."; }

function calulateAverageOften() {  
var jsonObjects = JSON.parse(data);
var suml=0;
for(var i=0; i<jsonObjects.length;i++){
  suml += Number(jsonObjects[i].often);  
 }
 return  suml/jsonObjects.length;
 }

然后为了过滤我的数据,我创建了一个开关功能:

function myFunction(value) { /
var userChoice = " ";  
userChoice = document.getElementById("choose").value; 
switch (userChoice) { //switch to do something depending of the user choice
                case "Everything": { 
                createReport(myArray);
                document.getElementById("demo2").innerHTML = "In this Research we had " + myArray.length + " participants." 
                break;
            } 
                case "facebook": {  //case of facebook
                var FB =[];
                FB = getObjects(myArray, "favorite", "facebook");  //has to find all the facebook in favorite in json file
                getObjects(myArray, "favorite", "facebook"); 
                createReport(FB);
                document.getElementById("demo2").innerHTML =  FB.length +" participants chose Facebook as their favorite Social Media"; 
        break;
            }

每个案例都会继续

现在在我的HTML页面上,用户可以选择一个社交应用,它会显示这个应用的数据,而我的平均功能显示了当用户选择一个应用时我想要的每个应用的平均值,它将仅显示该应用的平均值

谢谢

1 个答案:

答案 0 :(得分:0)

要过滤数组,只需使用.filter()函数

var facebookEntries = JSON.parse(jsondata).filter(function (entry) {
    return entry.favorite === 'facebook';
});
var facebookEntries = array.filter(function (entry) {
    return entry.favorite === 'facebook';
});

在你的例子中

 switch (userChoice) { //switch to do something depending of the user choice
    case "Everything": { 
        createReport(myArray);
        document.getElementById("demo2").innerHTML = "In this Research we had " + myArray.length + " participants." ;
        break;
    } 
    case "facebook": {  //case of facebook
       var FB = array.filter(function (entry) {return entry.favorite === 'facebook';});
       createReport(FB);
       document.getElementById("demo2").innerHTML =  FB.length +" participants chose Facebook as their favorite Social Media"; 
       break;
    }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter