Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify code that "toggles" an array item

I use lodash to insert an item into an array if it's not there, and remove it if it exists, kind of "toggling".

My code looks like this:

var items = ['a', 'b', 'c'];
var itemToToggle = 'a';

if (_.includes(items, itemToToggle)) {
    _.pull(items, itemToToggle)
}
else {
    items.push(itemToToggle)
}

Which seems not perfect enough. Can I simplify it to, ideally, have something like _.toggle(items, itemToToggle)?

like image 938
Sergei Basharov Avatar asked Nov 04 '15 09:11

Sergei Basharov


2 Answers

Another way to do it would be to use lodash's xor

var items = ['a', 'b', 'c'];
var itemToToggle = 'a';

new_array = _.xor(items, [itemToToggle])

return new_array // ['b', 'c']

Which will add the item if it does not exist, and remove if it does.

It does this by comparing the two arrays (items and [itemToToggle]) and returning a new array that is a merge of the two arrays, minus duplicates.

like image 73
S.Kiers Avatar answered Nov 17 '22 23:11

S.Kiers


Your code seems fine to me. The only thing, I can think of is using the length to see if an item was removed, and if not, add it:

function toggleValueInArr(arr, value) {
    var originalLength = arr.length; // cache the original length

    _.pull(arr, value).length === originalLength && arr.push(value); // check if the length is the same as the original - ie no item was not removed. If so, push it.

    return arr;
}
like image 40
Ori Drori Avatar answered Nov 18 '22 00:11

Ori Drori