Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: Push a word into array only if the array doesn't have that word already?

im trying to create a game where every time you enter a word into text field and press "Play", functions checks an array for the word you typed, if it is not there it will push it, if it is already there it will produce an error. I can’t figure out what is wrong. Been at it for hours.

I know i need to create an empty array where words will be stored, and i need to loop through the array and write an if statement basically saying if array item does not equal to the field value then push it into array otherwise display an error message. It seems like a simple problem but i can’t figure out what i am doing wrong.

The next part of the game, i will have to only push a word that is not in the array and it also has to start with the same name that the last word in the array ended on. But i am not there yet.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you so much for your help.

HTML

<body>
   
    <div id="main-container">
    
    <input type="text" id="field" class="button">
    <div id="message"></div>
    <button class="button" id="play">Play</button>
    
</div>


    <script src="index.js"></script>
</body>
JS

const field = document.querySelector('#field');
const message = document.querySelector('#message');
const playBtn = document.querySelector('#play')


let usedCities = ['york']

playBtn.addEventListener('click', function() {
    let fieldView = field.value;
    


    for (let i = 0; i < usedCities.length; i++) {
       if (usedCities[i] !== fieldView) {
        usedCities.push(fieldView) 
       } else {
        message.textContent = "ERROR"
       }
        
        
    }

    
})

This is basically as far as I got but it doesn’t work.

Thank you so much.

>Solution :

You can check for array values with array.includes

const usedCities = ['Copenhagen'];
const fieldView = 'Copenhagen';

if(!usedCities.includes(fieldView)){
    usedCities.push(fieldView)
}

console.log(usedCities);

Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading