Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
lodash toggle array element
/**
* descructive
* https://github.com/lodash/lodash/issues/1677
*/
function toggle(collection, item) {
var idx = _.indexOf(collection, item);
if(idx !== -1) {
collection.splice(idx, 1);
} else {
collection.push(item);
}
}
// es6 version
import { indexOf, without } from 'lodash';
export default function toggleItemInArray(collection, item) {
const index = indexOf(collection, item);
if (index !== -1) {
return without(collection, item);
}
return [...collection, item];
}
// tests
import toggleItemInArray from '../toggleItemInArray';
it('toggles item properly', () => {
expect(toggleItemInArray([], 'a')).toEqual(['a']);
expect(toggleItemInArray(['a', 'b'], 'a')).toEqual(['b']);
});
// lodash xor
_.xor([1], [2]); // = [1, 2]
_.xor([1, 2], [2]); // = [1]
@AleksandrZhukov
Copy link

AleksandrZhukov commented May 29, 2018

what about xor from lodash?

@Martian2Lee
Copy link

Martian2Lee commented Jul 5, 2018

_.xor([1], [2]);
= [1, 2]

_.xor([1, 2], [2]);
= [1]

@chodorowicz
Copy link
Author

chodorowicz commented Oct 31, 2019

Oh yeah, _.xor seems like a much better option 😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment