I have a set of buttons, which when clicked trigger a function which toggles their ID to an array called MyArray
function AddToArray(a, v) {
var v = this.id
var a = myArray
var i = a.indexOf(v);
if (i === -1)
a.push(v);
else
a.splice(i,1);
}
I want to use this same function for a different set of buttons. Instead of toggling their IDs to MyArray, I wish to toggle them to MySecondArray
At the moment, I simple have two separate functions, but it seems wrong to repeat code.
I considered adding a data-attribute to the buttons with a value of MyArray or MySecondArray and then turning this string into a variable to push to the relevant array. I understand though that using functions such as eval() can be insecure.
Therefore, I am wondering what the best way to do this is, in terms of reusing functions in general?