Blue
Blue

Reputation: 251

Can I push into an array from a set?

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.

fiddle

'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

Answers (2)

Davi
Davi

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

Roman Mahotskyi
Roman Mahotskyi

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

Related Questions