I'm trying to make an array that if a value doesn't exist then it is added but however if the value is there I would like to remove that value from the array as well.
Feels like Lodash should be able to do something like this.
I'm interested in your best practises suggestions.
Also it is worth pointing out that I am using Angular.js
* Update *
if (!_.includes(scope.index, val)) { scope.index.push(val); } else { _.remove(scope.index, val); }
To push an element in an array if it doesn't exist, use the includes() method to check if the value exists in the array, and push the element if it's not already present. The includes() method returns true if the element is contained in the array and false otherwise. Copied!
The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.
Examples of push in JavaScript and common errors To avoid this error you need to remember that push changes the array, and returns the new length. If you reassign the variable with the return value from push() you are overwriting the array value.
The Lodash. flatten() method is used to flatten the array to one level deep. Syntax: flatten( array ) Parameter: This method accepts single parameter array that holds simple array or array of arrays. Return Value: The return type of this function is array.
You can use _.union
_.union(scope.index, [val]);
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