Home > other >  How to run through an index of an array using higherorder function
How to run through an index of an array using higherorder function

Time:09-12

Hello so i have a json file of users who have an id. i made a function that has 2 parameters, parameter 1 is that you ask for the file name and parameter 2 is that you pass in an array of IDs. the problem i have is that i dont know how to compare the passed-in arrays's index versus the index of the json array of users. I want to make my code such that the function will return users whose id has been passed in the function parameter else, it should return all users in the default array. The following is my code:

let getUsers = (fileName,userIds = [1,2,3,4]) =>{

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) 
        {
            let arrUsers = JSON.parse(xhttp.responseText);
            
            //Filtering the code
            let relevant = arrUsers.map((data) =>{
                return data;
            }).filter((data,index) =>{
              
                return data.userid == userIds[index];
            })
            console.log(relevant);
        }
    };
    xhttp.open("GET", fileName, true);
    xhttp.send(); 

}

getUsers('users.json',[1,2])

CodePudding user response:

Hello and welcome to stackoverflow,
you did not provide the JSON file structure, but I assume that arrUsers it's something like :

// arrUsers
[
   {userid: ... , ... , ...}, 
   {userid:..., ..., ...}, 
   ...
]

So i suggest this solution

let relevant = arrUsers
.filter((data,index) =>{              
  return userIds.map(id => id.toString()).includes(data.userid.toString());
});

PS: I used map with userIds to assure that we are making a type to type comparaison.(here is string to string)

  • Related