Issue
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);
}
Solution
The Set
feature introduced by ES6 would do exactly that.
var s = new Set();
// Adding alues
s.add('hello');
s.add('world');
s.add('hello'); // already exists
// Removing values
s.delete('world');
var array = Array.from(s);
Or if you want to keep using regular Arrays
function add(array, value) {
if (array.indexOf(value) === -1) {
array.push(value);
}
}
function remove(array, value) {
var index = array.indexOf(value);
if (index !== -1) {
array.splice(index, 1);
}
}
Using vanilla JS over Lodash is a good practice. It removes a dependency, forces you to understand your code, and often is more performant.
Answered By - floribon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.