Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle values into and out of an array in Javascript

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.

like image 527
JPMox Avatar asked Sep 12 '13 13:09

JPMox


People also ask

How do you toggle values in an array?

const toggle = (arr, item, getValue = item => item) => { if (arr. some(i => getValue(i) === getValue(item))) return arr. filter(i => getValue(i) !==

Can you change elements of an array?

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.

How do you modify an array in JavaScript?

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.

How do I remove a specific element from an 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.


1 Answers

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.

like image 119
nnnnnn Avatar answered Oct 20 '22 09:10

nnnnnn