2

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?

4
  • 2
    That's exactly what parameters are for. It allows you to apply a function to different values. How is the function currently called? Commented Apr 27, 2021 at 20:23
  • 2
    Make myArray a parameter of the function and pass in the value you want? Though this function is already pretty strange in that the first thing it does is shadow any values that were passed to it. Commented Apr 27, 2021 at 20:23
  • 3
    var a = myArray does not make sense when you have a in the function declaration. Instead remove the line and a IS myArry OR MySecondArray if you pass it as first parameter Commented Apr 27, 2021 at 20:23
  • 2
    You're passing in arguments, then overriding them. Instead of assigning a and v, don't. Commented Apr 27, 2021 at 20:23

1 Answer 1

1

function toggleToArray(arr, id) {
    const i = arr.indexOf(id);
    return i === -1 ? [...arr, id] : arr.filter(val => val !== id);
}

// add if id does not exist
const myArr = toggleToArray(['a', 'b', 'c'], 'd');
console.log('toggltoarray.js: 8  myArr ', myArr);

// remove if exists
const myArr1 = toggleToArray(myArr, 'd');
console.log('toggltoarray.js: 12  myArr1 ', myArr1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.