Reputation: 227
I'm looking for a way to add and remove values from an array based on whether or not the value already exists in said array. I have an orders table set up that contains a select box, customer name and order ID and I'm looking to build this array based on the customer names.
Order Table
-----------
Select Customer Order_ID
------------------------------
[X] Joe 1
[X] Joe 2
[] Mark 3
[] Mark 4
[X] Mark 5
I'm creating a Customer array which pushes the selected customer names in the table. In the case above, if a selected name already exists in the array then just ignore said name, so the array should show....
//this
customerArray["Joe", "Mark"]
//not this
customerArray["Joe", "Joe", "Mark"]
However, it shouldn't remove the customer's name from the array until there are no selected records containing the customers name in said array.
Order Table
-----------
Select Customer Order_ID
------------------------------
[X] Joe 1
[] Joe 2
[] Mark 3
[] Mark 4
[X] Mark 5
This should still have
customerArray["Joe", "Mark"]
However...
Order Table
-----------
Select Customer Order_ID
------------------------------
[] Joe 1
[] Joe 2
[] Mark 3
[] Mark 4
[X] Mark 5
This should be
customerArray["Mark"]
I'm getting confused how to handle the duplicate names and removing them if the said name is no longer selected. Any help would be greatly appreciated.
Upvotes: 0
Views: 38
Reputation: 35491
A simple but not particularly efficient solution is to, every time before you add an element, check if it's already present in the array. If it's not, add it as intended, if it is, do nothing.
const array = [];
function add(element, arr) {
if (!arr.includes(element)) { // make sure element doesn't already exist before you add it
arr.push(element);
}
}
add("John", array);
add("John", array);
add("Mark", array);
add("Mark", array);
add("Mark", array);
console.log(
array // ["John", "Mark"]
);
The removal would have to be done in a similar way. Before trying to remove, you will have to check if there's anything to remove.
const array = ["John"];
function remove(element, arr) {
let idx = arr.indexOf(element);
if (idx !== -1) { // make sure element exists before removing it
arr.splice(idx, 1);
}
}
remove("Mark", array); // does nothing
console.log(
array // ["John"]
);
remove("John", array); // removes John
console.log(
array // []
);
A cleaner approach for this use-case is to use a data structure intended to hold unique values, which is a Set.
const set = new Set();
set.add("John");
set.add("John");
set.add("Mark");
set.add("Mark");
set.add("Mark");
console.log(
[...set.values()] // ["John", "Mark"]
);
A removal from a set is also fairly straightforward and handles the specifics under the hood.
const set = new Set(["John"]);
set.delete("Mark"); // does nothing
console.log(
[...set.values()] // ["John"]
);
set.delete("John"); // removes "John"
console.log(
[...set.values()] // []
);
Upvotes: 1