i have some code that takes input numbers and put them into a new array. How can i make it so my alert tells the user how many times the number is represented in the input? Exampel 0,4,4,2,3,4,1 would show "0 appears 1 time, 4 appears 3 times" and so on...I think im close but cant get the final part right...
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count = 0;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i] === parseInt(input)) {
count++;
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
I have changed your showTxt function
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count;
for (var i = 0; i < newArray.length; i++) {
count = 0;
for (var j = 0; j < newArray.length; j++) {
if (newArray[i] === newArray[j]) {
count++;
}
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
You could use the method from this gist like so:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.replace(/ /g, '').split(",").sort();
compressArray(split);
}
function compressArray(original) {
var compressed = [];
// make a copy of the input array
var copy = original.slice(0);
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 0;
// loop over every element in the copy and see if it's the same
for (var w = 0; w < copy.length; w++) {
if (original[i] == copy[w]) {
// increase amount of times duplicate is found
myCount++;
// sets item to undefined
delete copy[w];
}
}
if (myCount > 0) {
var a = new Object();
a.value = original[i];
a.count = myCount;
compressed.push(a);
}
}
for (var i = 0; i < compressed.length; i++) {
var message = compressed[i].value + ' appears ' + compressed[i].count + ' times.';
alert(message);
document.getElementById("print").innerHTML += message + '</br>';
}
};
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
Check this out, may be it'll helpful .
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
let countedValues = newArray.reduce(function(obj,val){
if(obj[val])
obj[val] += 1;
else
obj[val] = 1;
return obj
}, {})
for (let value in countedValues ) {
alert("Number " + value + " appears " + countedValues[value] + " times");
}
text = newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
Related
Alright, in my results for my program the results are displayed in a horizontal list (for e.x, HI,HELLO,HI,HELLO). I am trying to get these results to be in a numbered list from top to bottom.
function button() {
var inputArray = [];
var size = 4;
for (var i = 0; i < size; i++) {
inputArray[i] = prompt('Enter Element ' + (i + 1));
inputArray.sort();
document.getElementById("demo").innerHTML =
inputArray.map(function(x) {
return x.toUpperCase()
});
}
var str = String(inputArray).toUpperCase().split(",");
}
<button onclick="button();">Array</button>
<p id="demo"></p>
https://repl.it/repls/DangerousCloudyNumber
Just use an ordered list (<ol>) instead of a paragraph (<p>) and add list items (<li>) to the values while mapping them:
function button(){
var inputArray = [];
var size = 4;
for(var i=0; i<size; i++) {
inputArray[i] = prompt('Enter Element ' + (i+1));
inputArray.sort();
document.getElementById("demo").innerHTML = inputArray.map(function(x){ return "<li>"+x.toUpperCase()+"</li>"}).join("");
}
var str = String(inputArray).toUpperCase().split(",");
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<meta charset="utf-8">
<title>Program</title>
</head>
<body>
<button onclick="button();">Array</button>
<ol id="demo"></ol>
</body>
</html>
function button(){
var inputArray = [];
var size = 4;
var final_html = "<ol>"
for(var i=0; i<size; i++) {
input = prompt('Enter Element ' + (i+1));
if (input === null) {
document.getElementById("demo").innerHTML = inputArray.map(function(x){
if (x != null) {
final_html = final_html +"<li>"+x.toUpperCase()+"</li>";
}
});
document.getElementById("demo").innerHTML = final_html;
return; //break out of the function early
}else{
inputArray[i] = input;
}
inputArray.sort();
}
}
Need help with assignment. I need to create a button that uses a for loop to multiply each number in the array by the number after it into a second array and display the result. Lastly create another button that uses a while loop that divides each number in the array by the number after it into a third array and once more display the result. I have created a way to input numbers into an array "numbers" and display the array but do not know how to use for loops to display the quotient nor the product please help :(
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<p id="demo"></p>
<script>
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
</script>
Well, simply you could add these buttons and try to create some special logic for each button inside relevant function, for example MultiplyNumbers() and DivideNumbers():
<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>
In both functions firstly you should check if the main array has paired values via dividing length with 2 -> length % 2 == 0, then check if they're valid numbers with isNaN() function, if some value in pair is not valid you can define the result of this math equal 0 or what you want. Dividing function request also checking the second value in each pair with 0, cause you can't divide a number with zero(or you can).
So, the first function works via for loop, the second one via while loop.
The snippet below shows you this two functions, they're work correctly with this simple rules. If I've missed something you can tell me.
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
function MultiplyNumbers() {
let multNumbers = [];
if (myarray.length % 2 == 0){
let actions = myarray.length / 2;
for(let i = 0; i < actions; i++){
var tmult = (isNaN(myarray[i*2]) || isNaN(myarray[i*2+1])) ?
0 :
Number(myarray[i*2]) * Number(myarray[i*2+1]);
multNumbers.push(tmult);
}
document.getElementById("demo").innerHTML = multNumbers;
}
}
function DivideNumbers() {
let divNumbers = [];
if (myarray.length % 2 == 0){
let actions = myarray.length / 2;
let i = 0;
while(i<actions){
var tdiv = (isNaN(myarray[i*2]) || isNaN(myarray[i*2+1]) || Number(myarray[i*2+1]) == 0) ?
0 :
Number(myarray[i*2]) / Number(myarray[i*2+1]);
divNumbers.push(tdiv);
i++;
}
document.getElementById("demo").innerHTML = divNumbers;
}
}
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>
<p id="demo"></p>
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
// updated code
var secondArray=[];
function multiplyFunction(){
var temp = document.getElementById("num").value;
for(i=0;i<myarray.length;i++){
secondArray.push(Number(temp) * myarray[i]);
}
// show new array ..
text = "<ul>";
for (i = 0; i < myarray.length; i++){
text += "<li>" + secondArray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
//
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="multiplyFunction()">Multiply</button>
<button onclick="divideFunction()">Divide</button>
<p id="demo"></p>
</body>
</html>
function myFunction() {
var text = "";
var i;
for (i = 0; i <= 10; i++) {
text += + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
I want to add present i value into previous loop output value. This maybe a simple question. I have searched in google and stackoverflow. But, didn't get the desired result.
In above screenshot,
0 is the previous loop value + 1 is present i returns => 1
1 is the previous loop value + 2 is present i returns => 3
3 is the previous loop value + 3 is present i returns => 6
6 is the previous loop value + 4 is present i returns => 10
You need another persistent variable that keeps track of the last total that was concatenated with text:
function myFunction() {
var text = "";
var i;
var lastTotal = 0;
for (i = 0; i <= 10; i++) {
var newTotal = lastTotal + i;
text += + newTotal + "<br>";
lastTotal = newTotal;
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
(technically, you don't need the newTotal variable, but it makes the code's intent more clear)
You could also do this a bit more elegantly with reduce:
function myFunction() {
let text = '';
Array.from({ length: 11 }, (_, i) => i)
.reduce((lastTotal, i) => {
const newTotal = lastTotal + i;
text += newTotal + '<br>';
return newTotal;
}, 0);
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
You just need a second variable to hold the last value:
function myFunction() {
var text = "";
var sum = 0;
for (var i = 0; i <= 10; i++) {
sum += i;
text += sum + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
Keep a count of the last number:
function myFunction() {
var text = "";
var i;
var count = 0;
for (i = 0; i <= 10; i++) {
count += i;
text += count + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
You can use the function reduce to fill the operations and then use the function forEach to build the desired output.
function myFunction() {
var html = "";
Array.from({length: 10}, (_, i) => i + 1).reduce((a, c, i) => {
a[i] = (a[i - 1] || 0) + c;
return a;
}, []).forEach((n, i, arr) =>
(html += (arr[i - 1] || 0) + " + " + (i + 1) + " = " + n + "<br>"));
document.getElementById("demo").innerHTML = html;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
I think I'd just use an array so that you both have the previous sum, and can also use it with .join() for setting the HTML.
function myFunction() {
for (var i = 0, a = []; i <= 10; i++) {
a[i] = i + (a[i-1] || 0);
}
document.getElementById("demo").innerHTML = a.join("<br>");
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
<script>
var i=0;
var j="";
function app() {
j+=document.getElementById("demo").innerHTML="<button type='button'>Btn+i</button>";
}
</script>
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>
I am trying to append a button in the div tag every time user clicks add button.
Also I want the added button to be displayed like : Btn 1, Btn2,
Btn3..
A simple concatenation of #demo content and incrementation of a var i:
var i = 0;
function app() {
document.getElementById("demo").innerHTML += "<button type='button'>Btn " +
++i + "</button>";
}
<button type="button" onclick="app()">Add</button>
<div id="demo"></div>
You need to append HTML
var s = 0;
function app(){
s++;
var strHTML = "<button>Btn"+ s+"</button>"
document.getElementById('test').insertAdjacentHTML( 'beforeend', strHTML );
}
See this http://jsfiddle.net/euQ5n/226/
Or make it a little more readable.
<script>
var i = 0;
var j = "";
function makeButton(index) {
var $button = document.createElement('BUTTON');
$button.innerHTML = 'Button ' + index;
$button.onclick = function() {
alert('You clicked button:' + index);
};
return $button;
}
function onAddButtonClick() {
document.getElementById("demo").appendChild(makeButton(i));
i++; // increase number for next time;
}
</script>
<button type="button" onclick="onAddButtonClick()">Add</button>
<div id="demo">
</div>
var i1 = 0;
function app1()
{
var div = document.createElement('div');
div.innerHTML = "<button type='button'>Btn " + (++i1) + "</button>";
for (var child = 0; child < div.childNodes.length; child) {
document.getElementById("demo1").append(div.childNodes[child]);
}
}
var i2 = 0;
function app2() {
document.getElementById("demo2").innerHTML += "<button type='button'>Btn " +
++i2 + "</button>";
}
var d1s = new Date().getTime();
for (var j1 = 0; j1 < 1000; j1++) {
app2();
}
var d1e = new Date().getTime();
console.log((d1e - d1s) / 1000);
var d2s = new Date().getTime();
for (var j2 = 0; j2 < 1000; j2++) {
app1();
}
var d2e = new Date().getTime();
console.log((d2e - d2s) / 1000);
<div id="demo1"></div>
<div id="demo2"></div>
concatenation with innerHtml += is very slow
You need to change .innerHtml += ...
And increase i
var i=0;
function app()
{
j+=document.getElementById("demo").innerHTML+="<button type='button'> Btn"+i+"</button>";
i++;
}
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>
Can someone please help me. I don't know where I have gone wrong. The main thing not working is my start new game function but I don't know where I have gone wrong. Thanks in advance.
This is my fiddle
http://jsfiddle.net/Matt1990/jL7f3p39/25/
This is my javascript
enter code here
var Array = ["monitor", "program", "keyboard", "gaming", "harddisk", "software", "printer", "scanner", "firewall", "desktop", "system", "malware", "windows"];
var word;
var guessCount = 0;
var guess;
var input;
var wordLength;
var wordSubstring;
var currentWord;
function startGame() {
guess = "";
guessCount = 10;
word = Array[Math.floor(Math.random() * Array.length)];
currentWord = 0;
wordLength = word.length;
wordSubstring = currentWord.substring;
console.log(word);
var myElement = document.getElementById("button").innerHTML = "Click to guess";
var myPicElement = document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman10.jpg";
for (var count = 0; count < word.length; count++) {
guess = guess + "-";
}
document.getElementById("guess").innerHTML = guess;
}
function guessLetter() {
var correct = 0;
var inputBox = document.getElementById("guessinput");
input = inputBox.value;
for (var count = 0; count < wordLength; count++) {
if (input == word.substring(count, count + 1)) {
correct++;
guess = guess.substring(0, count) + input + guess.substring(count + 1, guess.length + 1);
document.getElementById("guess").innerHTML = guess;
}
}
if (correct == 0) {
guessCount--;
}
var url = document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman" + guessCount + ".jpg";
if (guess == word) {
document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman_win.jpg";
alert("You guessed the word correctly. You win!");
}
if (guess == 0 + word) {
document.getElementById("hangimage").src = "http://fetlar.kingston.ac.uk/pp/hangman0.jpg";
}
}
startGame();
document.getElementById("button").onclick = guessLetter;
function startNewGame(showMessage) {
guess = "";
guessCount = 10;
word = Array[Math.floor(Math.random() * Array.length)];
currentWord = 0;
wordLength = word.length;
wordSubstring = currentWord.substring;
console.log(word);
var myElement = document.getElementById("button").innerHTML = "Start New Game";
for (var count = 0; count < word.length; count++) {
guess = guess + "-";
document.getElementById("guess").innerHTML = guess;
}
}
and this is my HTML
<fieldset>
<div style="text-align: center;">
<h1>Hangman</h1>
<h2> Can you save the stick man? <h2>
<img id="hangimage" src="http://fetlar.kingston.ac.uk/pp/hangman9.jpg" />
<div id="guess" style="font-size: 2.5em; font-family: arial; color: red;">- - - - - - - </div>
<input id="guessinput" type="text" size="2" />
<button id="button">Click to guess</button>
<br/>
<div>Hint:The word is a computer-related term</div>
<button id="button">Start New Game</button>
</fieldset>
As i can see
HTML
<button id="button2">Start New Game</button>
JAVASCRIP
document.getElementById("button").onclick = guessLetter;
// add this
document.getElementById("button2").onclick = startNewGame;
http://jsfiddle.net/rnrlabs/jL7f3p39/30/