Search code examples
javascriptarraysfunctioninstantiation

How do I rewrite an instantiation to a function?


I would like to have a function called getSelectedValues which retrieves data from the options array instead of a variable called SelectedValues ( which is the way I have it now). The variable Selected Values currently gets the values that are true inside of the options array and assigns them to itself. I simply would like to make this a function instead. (something called getSelectedValues I would imagine) How do I achieve this?

var options = [
{
name: "Red Pepper",
"selected": false,
value: "5.99"   
},
  {
name: "Garlic",
"selected": true,
value: "5.99"   
},
      {
name: "Tomatoes",
"selected": true,
value: "5.99"   
}, 
]


  var SelectedValues = options.filter(function (option) {
  return (option.selected);
  });
 console.log(SelectedValues)

Solution

  • function getSelectedValues() {
       return options.filter(t => t.selected);
    
    }
    

    another way:

    getSelectedValues = () => options.filter(t => t.selected);