Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  78] [ 5]  / answers: 1 / hits: 126068  / 8 Years ago, fri, may 6, 2016, 12:00:00

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);
}

More From » arrays

 Answers
41

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.


[#62280] Wednesday, May 4, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylor

Total Points: 334
Total Questions: 100
Total Answers: 111

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;