I want to have a simple array of values, ie
var simpleArray = ["SE1","SE2","SE3"];
I want to check this array when an action happens (a click on a google map layer), that will pass a value to this function and either add the value to the array, or remove it from the array if it already exists.
I am now just a bit confused having seen .splice/push/inArray/indexOf (that doesn't work in IE)/grep (jQuery) - not sure what the best practice is.
const toggle = (arr, item, getValue = item => item) => { if (arr. some(i => getValue(i) === getValue(item))) return arr. filter(i => getValue(i) !==
To replace an element in an array:Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.
push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
Assuming the order of the items doesn't matter you can do something like this:
function toggleArrayItem(a, v) {
var i = a.indexOf(v);
if (i === -1)
a.push(v);
else
a.splice(i,1);
}
The .indexOf()
method does work in IE from version 9 onwards, but if you need to support older IE versions you can use a shim as explained at MDN. Or if you're using jQuery anyway use $.inArray()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With