Change a javascript function based on input in html

117 views Asked by At
dataset = data.map(function(d) 
              { return [ +d["Control 1"], +d["Control 2"],
                +d["Exp3"], +d["Exp4"], +d["Exp5"], +d["Exp6"] ]; 
              });

I want to be able to insert other +d's into the function based on user file input (I already have it in an array like ["exp7","exp8"...]). How do I write it so that the array is like +d ["exp7"] and so on and so forth?

I'm writing this in html.

Thanks!

1

There are 1 answers

1
tengbretson On

I think this would be a good place to make use of currying.

You could make a helper that does something like this:

function t(fields) {
  return function (data) {
    return fields.map(function (field) {
      return +data[field]
    })
  }
}

And then you would make use of it like:

dataset = data.map(t([
  "Control 1",
  "Control 2",
  "Exp3",
  "Exp4",
  "Exp5",
  "Exp6"
]));

This way you can pass in your other arrays of keys in directly.

edit: If your operating in an ES6 environment you could use the simple one-line combinator:

const t = fs => d => fs.map(f => +d[f])