Sort number javascript array - javascript

I need to sort the numbers that are drawn here from smallest to largest in the tables so that the table does not delete. How do I do that?
<html>
<head>
<title> Numery losowania </title>
<script>
var n1= new Array (9);
for(var i=0; i<n1.length;i++)
{
var rand= Math.floor(Math.random()*70);
n1[i] = rand;
}
document.writeln("<table border = \"1\"");
for(var i=0; i < n1.length;i++)
{
document.writeln("<tr><td>" + n1[i] + "</td></tr>");
}
document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>

Just add n1.sort(); before the loop.
The default sort order is according to string Unicode code points.
So you need to pass a function to it for sorting:
n1.sort((a,b) => a-b);
This will make sure that the lower numbers are first
For filling the array, use Array.from() this will save you some code
<html>
<head>
<title> Numery losowania </title>
<script>
var n1= Array.from({length: 9}, () => Math.floor(Math.random() * 70));
document.writeln("<table border = \"1\"");
n1.sort((a,b) => a-b); // sort the array
for(var i=0; i < n1.length;i++)
{
document.writeln("<tr><td>" + n1[i] + "</td></tr>");
}
document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>

<html>
<head>
<title> Numery losowania </title>
<script>
var n1= new Array (9);
for(var i=0; i<n1.length;i++)
{
var rand= Math.floor(Math.random()*70);
n1[i] = rand;
}
document.writeln("<table border = \"1\"");
n1.sort(function(a, b){return a - b});
for(var i=0; i < n1.length;i++)
{
document.writeln("<tr><td>" + n1[i] + "</td></tr>");
}
document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>
</html>

Related

How to get the proper Javascript output for the number pyramid

I am currently working on a 1/2 pyramid of numbers. I can get the output to total up the line and get everything but the * sign between the numbers. Hoping that someone out there can lend a helping hand. Here is the code that I have completed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Assignment 1</title>
<script>
var num = "";
var match ="";
var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";
for(var i=1; i<=size; i++)
{
if (i < size){
num = num + i + " "
} if (i==size) {
num =num + i }
total= total * i;
document.write(num + " = "+ total + "<br>");
}
}else {
alert("Please enter a number equal to or greater than 1");
}
var total="1";
</script>
</head>
<body>
<main>
<!-- Will show after the script has run -->
<h1>Assignment 1</h1>
</main>
</body>
</html>
-
I am looking for output like this
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
and so on.
Thanks again
You can use a loop like this and make the total time the new iteration value:
var total = 1;
var newList = [];
for(let i=1; i<=5; i++) {
newList.push(i);
total *= i;
console.log(newList.join('*') + '=' + total)
}
Run code snippet output:
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

Count to 100 using Javascript (in a div) [duplicate]

This question already has answers here:
using innerHTML in a loop is not properly displaying the set of json results
(4 answers)
Closed 5 years ago.
I wanne count to 100 in a div only using javascript. Why does only comes the last number.
Here is my code:
function test() {
for (var x = 1; x < 101; x++) {
document.getElementById("demo").innerHTML = (x + "<br />");
}
}function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<html>
<head>
<script src="function.js"></script>
</head>
<body>
<button type="button" onclick="test()">100</button>
<button type="button" onclick="leer()">Delete</button>
<div id="demo">
</div>
</body>
</html>
change document.getElementById("demo").innerHTML += (x + "<br />"); this line
function test() {
for (var x = 1; x < 101; x++) {
document.getElementById("demo").innerHTML += (x + "<br />");
}
}function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<html>
<head>
<script src="function.js"></script>
</head>
<body>
<button type="button" onclick="test()">100</button>
<button type="button" onclick="leer()">Delete</button>
<div id="demo">
</div>
</body>
</html>
Because the keep overriding the contents of the div with id "demo" by using innerHTML. You need to append the new number.
Please see this example (I updated your code).
function test() {
for (var x = 1; x < 101; x++) {
var current_contents = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = current_contents + (x + "<br />");
}
}function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<html>
<head>
<script src="function.js"></script>
</head>
<body>
<button type="button" onclick="test()">100</button>
<button type="button" onclick="leer()">Delete</button>
<div id="demo">
</div>
</body>
</html>
Because it happens so fast that you only see the last number. Do something like this:
var _counter = 1;
var _timer = null;
function test() {
_counter = 1;
_timer = setInterval(function(){
document.getElementById("demo").innerHTML = (_counter + "<br />");
_counter++;
if(_counter > 100) clearInterval(_timer);
}, 1000);
}
function leer() {
document.getElementById("demo").innerHTML = "Delete"
}
<div id="demo"></div>
<button onclick="test();">Count</button>
<button onclick="leer();">Delete</button>
Try using .append instead of .innerHTML

Sorting data in a stored array

Below is my code. I need to sort the array after the user input but can't figure out how to make that happen. I have tried several different things but nothing has worked including data.sort() and data.sort(function(a,b) { return a - b; }); but neither seems to be working. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Input integers into the array and then search the array to see if your input is present!</h1>
<p id="data">[]</p>
<input id="inputNumber" value="0" /> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0" /> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
for (var i = 0; i < 5; i++) {
data.push(prompt('enter integer ' + (i + 1)));
}
alert('Full array: ' + data.join(', '));
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for (var i = 0; i < data.length; i++) {
if (data[i] == toFind) return alert("found at " + i);
}
return alert("That number was not found");
}
function refresh() {
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>

Dynamically array input with Javascript

I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here

random no generate(1-9) using 9 <div> without no repitation,,,,,

I have tried to generate rnadom number(1-9) in 9 div's. How to avoid number repitations? But it's not working, why i cant get output? Thanks in advance.
Here is my code:
<html>
<head>
<title>Random_No</title>
<link rel="stylesheet" type="text/css" href="rno.css">
<script src="rno.js" ></script>
</head>
<body class="outer" onload=random()>
<div id="input1" ></div>
<div id="input2" ></div>
<div id="input3" ></div>
<div id="input4" ></div>
<div id="input5" ></div>
<div id="input6" ></div>
<div id="input7" ></div>
<div id="input8" ></div>
<div id="input9" ></div>
<script>
function random()
{
var a=new Array("input1","input2","input3","input4","input5","input6","input7","input8","input9");
x=a.length;
var ran=new Array();
for(var i=0;i<x;i++)
{
ran[i]=Math.floor(Math.random()*9);
}
for(var i=0 ; i<x ; i++)
{
document.getElementById("a[i]").innerHTML=ran[i];
}
}
</script>
</body>
</html>
Replace
document.getElementById("a[i]").innerHTML=ran[i];
By
document.getElementById(a[i]).innerHTML=ran[i];
And... why 2 loops ?
Because you only want a small set of items randomised with no repeats and to take each one, a Fisher-Yates shuffle would be very efficient here.
var inputs = [], i;
for (i = 1; i < 10; ++i) // get each input
inputs.push(document.getElementById('input' + i));
function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
var i = a.length, t, j;
a = a.slice();
while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
return a;
}
inputs = shuffleArray(inputs); // shuffle
for (i = 0; i < 9; ++i) // give values (already shuffled)
inputs[i] = i + 1; // there will be no repeats because we're counting up
Another way to generate randoms from a set-
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Random_No</title>
</head>
<body >
<div id= "input1"></div>
<div id= "input2"></div>
<div id= "input3"></div>
<div id= "input4"></div>
<div id= "input5"></div>
<div id= "input6"></div>
<div id= "input7"></div>
<div id= "input8"></div>
<div id= "input9"></div>
<script>
function random_no(){
var i=0, ran=[1,2,3,4,5,6,7,8,9];
while(i<9){
document.getElementById("input"+(++i)).innerHTML=
ran.splice(Math.floor(Math.random()*ran.length),1);
}
}
onload=random_no;
</script>
</body>
</html>
You need to change
document.getElementById("a[i]").innerHTML = ran[i];
to
document.getElementById(a[i]).innerHTML = ran[i];
because putting quotes around a[i] makes it look for an element whose id is actually "a[i]"
You can map the elements in another array, shuffle it and inject the random number in basically one chained operation using some array methods:
var divs = document.getElementsByTagName('div');
[].map.call(divs, function(e, i) {
return i;
}).sort(function() {
return (Math.round(Math.random())-0.5);
}).forEach(function(r, i) {
divs[i].innerHTML = r;
});
DEMO: http://jsfiddle.net/EsGL3/
You can use Array.sort() with a random comparator to re-order the values:
JSFIDDLE
function random()
{
var x = 9,
ids = [ 'input1', 'input2', 'input3',
'input4', 'input5', 'input6',
'input7', 'input8', 'input9'
],
values = [1,2,3,4,5,6,7,8,9],
i = 0;
Array.sort( values, function(a,b){ return Math.random() < 0.5 ? 1 : -1; });
for( ; i < x; ++i)
{
document.getElementById( ids[i] ).innerHTML = values[i];
}
}

Categories

Resources