Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lodash push to an array only if value doesn't exist?

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); } 
like image 587
Max Lynn Avatar asked May 06 '16 13:05

Max Lynn


People also ask

How do you avoid adding to an array if element already exists?

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!

How do you check if a value does not exist in an array JavaScript?

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.

Does push change array?

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.

What is Lodash flatten?

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.


1 Answers

You can use _.union

_.union(scope.index, [val]); 
like image 166
Afzal Hossain Avatar answered Oct 12 '22 11:10

Afzal Hossain