Skip to content

Instantly share code, notes, and snippets.

@chodorowicz
Last active February 15, 2021 21:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chodorowicz/1a77655681a3f67ea36de974a1357882 to your computer and use it in GitHub Desktop.
Save chodorowicz/1a77655681a3f67ea36de974a1357882 to your computer and use it in GitHub Desktop.
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

what about xor from lodash?

@Martian2Lee
Copy link

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

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

@chodorowicz
Copy link
Author

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