Making new array with array.length - javascript

How can I sort array.length numerically? In this image my numbers generator should be ordered in descending order.
I tried creating a new array with the push function. My code is as follows:
var newArray = [];
newArray.push(myArray.length);
Unfortunately this doesn't work. I'm a beginner in javascript and I haven't been able to find another solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="hack.js" defer></script>
</head>
<body>
<div id="demo" style="width: 500px;border: 1px solid black;"></div>
<script>
var myNumbers = '';
for (var i = 10; i <= 40; i++) {
var myArray = [];
for (var j = 2; j < i; j++) {
if (i % j == 0) {
myArray.push(j);
}
}
myNumbers += "<p>" + i + " number of generators = " + myArray.length + '</p>';
}
document.getElementById("demo").innerHTML = myNumbers;
</script>
</body>
</html>

var myNumbers = [];
for (var i = 10; i <= 40; i++) {
var myArray = [];
for (var j = 2; j < i; j++) {
if (i % j == 0) {
myArray.push(j);
}
}
var value = { int: i, length: myArray.length, html:"<p>" + i + " number of generators = " + myArray.length + '</p>' }
myNumbers.push(value);
}
myNumbers.sort(function(a, b){
return b.length - a.length;
});
document.getElementById("demo").innerHTML = myNumbers.map(function(d) { return d['html']; }).join('')

first you can store mappings of numbers and their generator count in an array of objects. Then you can sort this array using a comparator function. The iterate over this array add elements based on this sorted array.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="hack.js" defer></script>
</head>
<body>
<div id="demo" style="width: 500px;border: 1px solid black;"></div>
<script>
var myNumbers = '', myArray = [];
for (var i = 10; i <= 40; i++) {
var count = 0;
for (var j = 2; j < i; j++) {
if (i % j == 0) {
count++;
}
}
myArray.push({number: i, generators: count});
}
myArray.sort(function(a,b){
return b.generators - a.generators;
});
for(var i=0; i<myArray.length; i++)
myNumbers += "<p>" + myArray[i].number + " number of generators = " + myArray[i].generators + '</p>';
document.getElementById("demo").innerHTML = myNumbers;
</script>
</body>
</html>

Related

Multiplication Table in javascript and how about to align the row

I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>
Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/
Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>
#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example

Bind JS Pyramid in HTML

I created a pyramid using JavaScript and below is the code that I tried so far using for loop:
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) { //Outer loop
for (var j = 1; j <= i; j++) { //Inner loop
output += '* ';
}
console.log(output);
document.getElementById('result').innerHTML = output;
output = '';
}
}
Pretty basic! But I am trying to bind the result with HTML element, say with div as follows:
document.getElementById('result').innerHTML = output;
Instead it shows five stars in a row rather than the format in JS seeing in the console. Anything that I am missing here?
Full Code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= i; j++) {
output += '* ';
}
console.log(output);
document.getElementById('result').innerHTML = output;
output = '';
}
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id="result"></div>
</body>
Currently, you are resetting the innerHTML at the end of each loop iteration; either use += to append HTML or append all the output together first, then set the innerHTML. Also, you will need to use the <br> tag to create line breaks in HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
var rows = 5;
var output = '';
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= i; j++) {
output += '* ';
}
output += "<br/>";
}
document.getElementById('result').innerHTML += output;
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id = "result"></div>
</body>
</html>
const result = document.querySelector("#result");
function generatePyramid(max = 5) {
result.innerHTML = "";
const length = 2 * max - 1;
for (let i = 1; i <= max; i++) {
let s = "*".repeat(i).split("").join(" ");
s = s.padStart(
s.length + Math.floor((length - s.length) / 2)
).padEnd(length);
const div = document.createElement("div");
div.innerHTML = s.replace(/\s/g, " ");
result.appendChild(div);
}
}
// generatePyramid(); // base 5 stars
generatePyramid(11); // base 11 stars
// generatePyramid(21); // base 21 stars
<h1>Pyramid</h1>
<div id="result"></div>

how do I number an array (in a list)

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();
}
}

Get index from multidimensional array

I have a multidimensional array like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
{
if (squares[i] == null)
{
squares[i] = ''+j;
}
else
{
squares[i].push('' + j);
}
}
}
I want to get the the index from the multidimensional array when I click on a square:
angular.element('.click').click(function() {
var squareId = angular.element(this).attr('id'); //Rutans id
for(var k = 0; k <= 8; k++)
{
var squareIndex = squares[k].indexOf(squareId);
}
console.log(squareIndex);
But this only results in -1 by console.log. Anyone who can help me?
Using indexOf() you are only checking that the ID exists within that array. So if it occurs in the first array, it will continue to loop over them return -1 overwriting the previous value.
What you need to do is stop the loop when you find it and return k, the index of the array you are currently iterating through.
Here is a fiddle, hope this helps
Fiddle
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
{
if (squares[i] == null)
{
squares[i] = ''+j;
}
else
{
squares[i].push('' + j);
}
}
}
console.log(squares);
$('a').on('click', function(){
var squareId = $(this).attr('id');
var squareIndex = 0,
numberIndex = 0;
for(var k = 0; k < squares.length; k++)
{
squareIndex = squares[k].indexOf(squareId);
if (squareIndex > -1) {
numberIndex = squareIndex;
squareIndex = k;
break
}
}
alert('NumberIndex: '+ numberIndex+' ParentSquareIndex: '+ squareIndex);
});
please see here http://plnkr.co/edit/aldjCQRchgESR7IWn367?p=preview i hope that will help.
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello !</p>
<table>
<tr ng-repeat="lines in squares track by $index ">
<td ng-repeat="nr in lines track by $index" ng-click="getMyId(nr)">{{nr}}</td>
</tr>
</table>
</body>
</html>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
var squares = [];
for(var i = 0; i <= 8; i++)
{
squares[i] = [];
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
{
if (squares[i] === null)
{
squares[i] = ''+j;
}
else
{
squares[i].push('' + j);
}
}
}
$scope.squares = squares;
$scope.getMyId = function(id){
alert(id);
}
console.log(squares);
});

How to make this table of prime numbers display in reverse

I have created a table that displays all prime numbers from 2-1013 but it is displaying from the bottom right to the top left and I would like it to display from the top left to the bottom right. How would I achieve this?
<!DOCTYPE HTML Public>
<html>
<head>
<title>Prime Numbers</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body onload='CalcPrime()'>
<script type='text/javascript'>
function CalcPrime() {
var setIt = 0;
var count = 0;
var num = 3;
var primeArray = new Array();
primeArray.unshift(2)
while (count < 169) {
setIt = 0;
var i = 2
while (i < num + 1) {
if (num % i == 0) {
setIt = setIt + 1;
}
i = i + 1
}
if (setIt < 2) {
primeArray.unshift(num);
count = count + 1;
}
num = num + 1;
}
var a;
document.write("<table cols='10' border='1'>");
document.write("<tr><th colspan=10 border='1'>Prime Numbers 2-1013</th></tr>");
for (var it = 0; it < 161; it = it + 10) {
document.write("<tr>");
for (var colm = 0; colm < 10; colm++) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
}
</script>
</body>
</html>
If you push your values onto the array instead of unshifting them, that will put them at the end of your array instead of the start. Which would do exactly what you want.
This will get you close. Basically, instead if incrementing your indices, decrement them. Instead of starting with 0, start with the final number and go down to zero. In other words, reverse your loop.
for (var it = 161; it >= 0; it -= 10) {
document.write("<tr>");
for (var colm = 10; colm >= 0; colm--) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
It's not perfect yet, but this will get you close for now. I'll edit after I tweak it a bit.
Before writing the table, reverse the primeArray variable by adding:
primeArray = primeArray.reverse();

Categories

Resources