Reputation: 251
How should I go about doing this, can I even push or is there some other method I can use to add the set to my global array?
I'll just give my javascript for now if you really need the HTML and CSS, I can give it but I don't think it is needed.
Like the set does what it's supposed too, but I'm not sure if its being saved into an actual Array that I'll be able to call later on down the line or not.
I don't think the push at the end is needed, or is it doing anything at the moment.
Guess I should give more concept, I am building a calculator and trying to keep from multiple operators being shown.
'use strict';
const input = document.querySelector('#input'), // input/output button
numbers = document.querySelectorAll('.numbers div'), // number buttons
operators = document.querySelectorAll('.operators div'), // operator buttons
result = document.querySelector('#result'), // equal button
clear = document.querySelector('#clear'); // clear button
let numberInput = []
let operatorsInput = []
document.querySelectorAll('.numbers div').forEach(buttonPress => {
buttonPress.addEventListener('click', (event) => {
numberInput.push(parseInt(event.target.textContent));
console.log(numberInput)
});
});
document.querySelectorAll('.operators div').forEach(buttonPress => {
buttonPress.addEventListener('click', (event) => {
operatorsInput.push(event.target.textContent);
// operatorsInput.from(noDuplicates);
let noDuplicates = [...new Set(operatorsInput)];
let operatorsND = Array.from(noDuplicates)
console.log(operatorsND);
operatorsInput.push(operatorsND)
});
});
Upvotes: 0
Views: 75
Reputation: 4157
If I understood correctly, the solution is as simple as this (I skipped some parts of your example code):
// ... elided ...
let numberInput = []
let operatorsInput = new Set(); // <-- make a Set by default
document.querySelectorAll('.numbers div').forEach(buttonPress => {
// ... elided ...
});
document.querySelectorAll('.operators div').forEach(buttonPress => {
buttonPress.addEventListener('click', (event) => {
operatorsInput.add(event.target.textContent); // <-- "push" to the Set
console.log(...operatorsInput.values()) // <-- read & display values in the Set
});
});
This ensures you have each operator only once inside operatorsInput
.
Upvotes: 1
Reputation: 6655
Yes, you can push.
This line of code allocates memory and place all elements from the set to the newly created array.
let noDuplicates = [...new Set(operatorsInput)];
Upvotes: 0