Make .map dynamic

I would like to make dynamic what to filter for depending on what the users response is when prompted. Currently its hard coded which is fine but when I add more data is will become too many lines of code. There obviously must be a way to make it dependant on what the user responds to.
Essentially I want to replace the hard coded Name and Age with whatever a user responds to when prompted.

CodePen below.

Note it will ask 2 questions. If you respond Age and then respond 21 you will get two players over then the age of 21.


Hi @fuell.python

What exactly are you trying to do?

Replace the predefined names ‘Name’ and ‘Age’ with something that is not fixed, something a user can decide when prompted.
So the user is prompted with What do you want to filter for instead of only fixed filtering for either name or age.

I meant what is the code you have written supposed to do? Are you filtering an array based on user input?

Yes that’s what I want. Filter an array by input

If that is the case, I don’t think prompting a user for input immediately after navigating to a web page is appropriate. It provides for a poor user experience. If I were you, I would use a form instead to get user input.

I assume you want the user to input a variable name like Age and then criteria for filtering. But how would the user input the filtering criteria because there are several of them. For example you can filter all those who are:

  • Older than a certain age
  • Younger than a certain age
  • Between
  • Exactly

How will the user input those values?

Yes I was going to make a form but I wanted to get the logic working first before making it pretty etc. Assume there are many more items in the list like name, age, height, speed etc.
Instead of .filter(({Name}) I want the user to be able to choose from a list of items on the screen that I show them. {name} is replaced with what ever the user selects from the screen. Essentially the .filter becomes dependant on what the user wants it to be (not hard coded)

If I have understood what you are trying to do, then that should be straight forward like below. Though you have not answered my question on how you will obtain the filtering criteria from the user. I assume you have it figured out.

const selectedFilter =  "Age" // Obtain from window prompt
const askValue = 23 // Obtain from window prompt

const filteredPlayers = players.filter((player) => {
     if(!player.hasOwnProperty(selectedFilter)) return false;
     return player[selectedFilter] >= askValue ;  // How will you know the user wants greater, less or equal


I have seen you first applying map on the array. I wonder why that is.

Hi nibble,

I forgot to say thanks for your help.


It helped.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.