Show full ArrayList in HTML - javascript

I am trying to show the whole array separated with a comma in the HTML body. So far, the whole ArrayList is the result of the multiplication of specific values, so if the value is 2, then ArrayList will be (2,4,6,8,10).
I have created the multiplication function using js and in console, I can see the ArrayList. But whenever I am trying to show this list in HTML using innerHTML, I only can see 10 (for multiplication of 2), but can not visualize the whole list.
function showData() {
var theSelect = demoForm.part;
var secondP = document.getElementById('secondP');
var num = theSelect[theSelect.selectedIndex].value
console.log("this is" + num)
for (var i = 1; i <= 5; i++) {
result = i * num;
console.log("List is" + result);
}
secondP.innerHTML = ('Its Standerd Pack is: ' + theSelect[theSelect.selectedIndex].value + " we have to choose" + result);
}
<p id="secondP"></p>
Current output is:
Its Standard Pack is: 2 we have to choose 10
Expected output:*
Its Standard Pack is: 2 we have to choose 2,4,8,10
Any suggestion on how to do that. Thank you very much

You need to make result an array and push onto it, not reassign it.
function showData() {
var secondP = document.getElementById('secondP');
var num = 2
console.log("this is" + num)
let result = [];
for (var i = 1; i <= 5; i++) {
result.push(i * num);
}
secondP.innerHTML = ('Its Standerd Pack is: ' + num + " we have to choose " + result.join(", "));
}
showData();
<p id="secondP"></p>

Sorry if I got it wrong but if you were having trouble to show the items in an array separated by a comma (or anything else),
the simplest solution I have is arr.join(", ")
or a neat code
const arr = [1, 2, 3, `a`, `b`, `c`];
function showFullArrayList(arr) {
console.log(arr.join(`, `));
}
showFullArrayList(arr);

Related

Javascript median using for

So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".
function Media()
{
var n = prompt("number of elements?");
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong
You should parse the result of prompt to an integer;
How to convert a string to an integer in JavaScript?
function Media() {
var n = parseInt(prompt("number of elements?"));
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
m = parseInt(m);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
Media();
<div id='rezultat' />
You should also parse the result of prompt using parseInt
var m = parseInt(prompt("insert # " + i));
s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.

Need to Map two or more datasets and display as Chart using javascript

So, I've written a small script using Javascript, where it reads the content of the text editor and does arithmetic/other operations according to what's written in it.
Like if I type "col0 + col1", it will add the two columns and display a Pie/Bar chart.
But this is what I'm having hard time doing, "col0 + col1 + 2000", where the 2000 should be added to the final result.
if (formula.split(" ")[nCnt + 1] == "+") {
if (isNumeric(formula.split(" ")[nCnt])) {
numTo = formula.split(" ")[nCnt];
sym = formula.split(" ")[nCnt + 1];
sym += numTo;
// debugger;
} else {
sym = formula.split(" ")[nCnt + 1];
}
secondaryData[secondaryData.length - 1] = secondaryData[value].map(function (num, idx) {
//if (isNumber(numTo)) {
num += sym;
res = num + secondaryData[formula.split(" ")[nCnt + 2]][idx];
return res;
// }
});
}
My logic is, splitting everything using space. Then if there's a "+" in the next index, check if there's a number in the current index and store the value in a var.
Then using map function, add everything at last, but it performs a Var+integer thing not a integer+integer one. Also I want to know how I can add more columns to this like "col0 + col1 + col2", etc.
You have the first step which is checking whether the value is a number, but in order to do math you will need to parse the value.
if (isNumeric(formula.split(" ")[nCnt])) {
numTo = parseFloat(formula.split(" ")[nCnt]);
sym = parseFloat(formula.split(" ")[nCnt + 1]);
sym += numTo;
} else {
sym = formula.split(" ")[nCnt + 1];
}
If you wanted to run this for all columns, first you would need to group them in an array, then you could run the function for each value in the array:
const formulas = [col1, col2, col3, col4];
for (const formula of formulas) {
if (isNumeric(formula.split(" ")[nCnt])) {
numTo = parseFloat(formula.split(" ")[nCnt]);
sym = parseFloat(formula.split(" ")[nCnt + 1]);
sym += numTo;
} else {
sym = formula.split(" ")[nCnt + 1];
}
}
This code doesn't quite run because nCnt is not defined for me, but hopefully it points you in the right direction.

javascript replace string/html from array

I try to create a system replacement for ToolTip.
I already create a version but its not quite optimal (search a better way to do it)
here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/
I create a dictionary (array[key]->value). the array is order by length of the key.
each key is a word or an expression, the value is the definition of the expression.
So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text).
because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code.
You could make comment or post a new way to do it. maybe someone already did it.
Clarification :
I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it?
html :
<div class="container">
one two three four five six seven eight nine ten
</div>
javascript :
$(function() {
var list = [
{'k':'one two three four five','v':'First five number.'},
{'k':'four five six seven','v':'middle number.'},
{'k':'six seven eight','v':'second middle number.'},
{'k':'two','v':'number two.'},
{'k':'six','v':'number six.'},
{'k':'ten','v':'number ten.'}
];
$(".container").each(function(){
var replacement = new Array();
for (i = 0; i < list.length; i++) {
var val = list[i];
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
replacement[rString + "_k"] = htmlEncode(val["k"]);
replacement[rString + "_v"] = htmlEncode(val["v"]);
var re = new RegExp("(" + val["k"] + ")","g");
$(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) {
var newItem = '<span class="itemWithDescription" '
+ 'data-title="' + rString + "_v" + '">'
+ rString + "_k"
+ '</span>';
return html.replace(re, newItem);
});
}
for (var k in replacement){
$(this).html($(this).html().replace(k,replacement[k]));
console.log("Key is " + k + ", value is : " + replacement[k]);
}
});
$(document).tooltip({
items:'.itemWithDescription',
tooltipClass:'Tip',
content: function(){
var title = $(this).attr("data-title");
if (title == ""){
title = $(this).attr("title"); //custom tooltips
}
return title;
}
});
});
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression.
for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ;
http://jsfiddle.net/forX/Lwgrug24/3/

Javascript multidimensional array updating specific element

I have a string that has been converted into an 2D Array in js.
board = "...|.X.|...|"
It is used to represent a game board
each . represents a space
each | represents a row
each X represents a wall
EDIT: code below for the 2d array creation
var src= "...|.X.|...|";
board = src.split(/\|/g);
for (var i = 0; i < board.length; i++) {
var cells = board[i].split('');
for (var j = 0; j < cells.length; j++) {
cells[j] = parseInt(cells[j]);
}
board[i][j] = cells;
console.log(board[1][1])
//returns 'X'
when i access board[i][j] it returns correctly:
[0][0] = "."
[1][1] = "X"
[1][2] = "."
etc etc
I want to update the specific element with a string representing a piece.
However when i insert into an element like so:
board[0][0] = "piece4"
The array returns in firebug as so:
board = "piece4|.X.|...|"
When it should look like:
board = ".piece4.|.X.|...|"
Why are elements [0][1] and [0][2] being overwritten? Am I not understanding arrays of array index access correctly in js?
I just had the same problem, but it had a more complex reason and I want to add it, in case someone finds this page searching for the same problem I had:
I had created and filled a 2-dimensional array like this:
var foo = Array(n).fill(Array(n).fill(0));
which creates a 2-dimensional n*n array filled with zeroes.
Now when I tried to overwrite a cell like this
foo[1][1] = 1;
I ended up with these values:
[[0,1,0],
[0,1,0],
[0,1,0]]
which is really surprising IMHO.
The reason for this was, that there has only been one row, which had internally been referenced three times. So when I changed the first index in "the second" row, it effectively changed all rows.
Bottom line: don't use Array.fill to create multi-dimensional arrays!
PROBLEM:
I'm betting that you have a one-dimensional array with strings stored in each. So your array actually looks like:
array (
[0] => '...',
[1] => '.X.',
[2] => '...'
)
When this is what you want:
array (
[0] => array (
[0] => '.',
[1] => '.',
[2] => '.'
),
[1] => array (
[0] => '.',
[1] => 'X',
[2] => '.'
),
[2] => array (
[0] => '.',
[1] => '.',
[2] => '.'
)
)
SOLUTION:
When constructing your 2D array, make sure you explicitly declare each entry in board as an array. So to construct it, your code might look something like this:
board = new Array();
rows = 3;
for (var i = 0; i < rows; i++)
board[i] = new Array('.', '.', '.');
An other way to create a 2D array in javascript is to use Array.from function
var 2Darr = Array.from(Array(5), () => {
return new Array(5).fill(0)
})
This will create a 5 x 5 array completely filled with 0. Array.from takes two parameters, the first one is an javascript iterable Object to extract the array from, the second one is an optional callback where we can specify something to apply to the array elements.
Accessing the element can be done simply like in other languages.
I ran into a similar problem. So after reading a lot... this finally suited my needs.
myArr = [1,1,1];
var arr = new Array();
for (var i = 0; i < 10; i++) {
arr[i] = Array.from(myArr);
}
//lets edit 3 positions
arr[0][1]= -1;
arr[3][2]= 100;
arr[8][0] = 8080;
for(var i=0; i<10; i++){
console.log(i + " === " + arr[i]);
}
OUTPUT:
if you noticed only the edited index values changed... nothing else
0 === 1,-1,1 <---
1 === 1,1,1
2 === 1,1,1
3 === 1,1,100 <---
4 === 1,1,1
5 === 1,1,1
6 === 1,1,1
7 === 1,1,1
8 === 8080,1,1 <---
9 === 1,1,1
Two remarks here:
Arrays start with index 0 in every dimension.
If you access a string as a 2D array, every element is a char rather than a string.
So if you write board[0][0] = 'X'; then you get the right behavior (and that changes the first character of the string, not the second).
The situation and solution given above is pretty simple. The issue of updating specific values in a list of objects (often referred to as an array, but that's a discussion for a different time) has more practical and industrial application. The problem you tend to run into is thinking that looking at a value in a specific cell, e.g. my_array[0][0] returns 'some value' will also let you change that value through an assignment e.g. my_array[0][0] = 'new value'. You will find that depending on how you defined your array, the change shows in the same row across the columns, not what you are needing.
Look at the example code as an illustration of creating, and managing a multidimensional list of objects (array).
<html>
<head>
<title>JavaScript Object List/Array</title>
<script>
//Make a JavaScript array that can manage data of inventory between different locations over time.
var list_of_brands = ["BMW","Harley Davidson","Honda","Kawasaki"];
var list_of_locations = ["Dayton","Cincinnati"];
//a month of data
var DAYS_IN_A_MONTH = 30;
var calendar = [];
for(day_of_sales = 1; day_of_sales <= DAYS_IN_A_MONTH; day_of_sales++){
//hold your locations
var shop_location = [];//You need to create a new array for each day - that's part of the trick!
for(location_index = 0;location_index < list_of_locations.length;location_index++){
//set up some starting inventory
var inventory = [];//You need to create a new array for each location - that's part of the trick!
for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){
inventory[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0};
};//end inventory loop
shop_location[list_of_locations[location_index]] = {"city":list_of_locations[location_index],inventory};
}//end location loop
calendar[day_of_sales] = {"Day": day_of_sales, shop_location};
}//end calendar loop
//check your work
console.log('calendar:'); console.log(calendar);
console.log('shop_location:'); console.log(shop_location);
console.log('specific information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//returns 'BMW'
console.log('change Dayton.BMW information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand="Triumph");//change value
console.log('check work (Dayton.BMW): '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//check work - PASS
console.log('check work (Cincinnati.BMW): '); console.log(calendar[1].shop_location["Cincinnati"].inventory["BMW"].brand);//check work other location - PASS!!
//Make some lasting and specific changes
console.log("Now make a change in the month's value over showing a sale on the 13th");
var sale_date = 13;
console.log("date of sale " + sale_date + "th");
var original_number_on_hand = calendar[sale_date].shop_location["Dayton"].inventory["BMW"].on_hand;
console.log("original_number_on_hand on that date: " + original_number_on_hand);
var number_of_units_sold = 3;
console.log("number_of_units_sold on that date: " + number_of_units_sold);
var new_inventory_level = original_number_on_hand - number_of_units_sold;
console.log("new_inventory_level: " + new_inventory_level);
for(date_index = sale_date; date_index <= DAYS_IN_A_MONTH; date_index ++){
calendar[date_index].shop_location["Dayton"].inventory["BMW"].sold = number_of_units_sold;
calendar[date_index].shop_location["Dayton"].inventory["BMW"].on_hand = new_inventory_level;
}
console.log("Show change in inventory");
console.log(list_of_locations[0]+" has " + calendar[10].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[10].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[11].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[11].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[12].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[12].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[13].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[13].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[14].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[14].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[15].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[15].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[16].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[16].shop_location["Cincinnati"].inventory["BMW"].on_hand);
//add new items to a shop's inventory
var inventory_2 =[];
for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){
inventory_2[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0};
};//end inventory loop
console.log("show inventory_2");console.log(inventory_2);
console.log("add inventory");inventory_2["Indian"] = {"brand": "Indian", "on_hand": 10,"sold": 0};
console.log("show updated inventory_2");console.log(inventory_2);
</script>
</head>
<body>
<p>look in the JavaScript console for output</p>
</body>
</html>

how to write/rewrite in a <p> using a function in javascript

was hoping if anyone could help. I would like to be able to have it that whenever the arrays I pass into the function change it will display these values in a paragraph tag.
At the moment it doesn't rewrite it and I want it to display like it's steps (i.e 1. ... 2. ...) but it doesn't update the step number or take a new line either. This function is called in another function.
The code so far is:
//javascript code
//cred & grade are arrays
function breakdown(cred, grade){
var change = document.getElementById('bdown'); //'bdown' is the id of the <p>
var to;
var a = 1;
var x = 0;
for(var b = 0; b<cred.length; b++){
//alert(a)
to += a + ". (" + cred[b] + " x " + grade[b] + ")" + "<br /"; //show the step number and the values then take a new line
a++; //increment the step number
change.innerHTML=bdown.innerHTML.replace(change.textContent,to ); //wish to change <p>
}
}
//html code
// the paragraph wish to change
<div id="how"; style="color:white;display: none">
<p id="bdown"></p>
</div>
Using code:
var to = "";
for(var b = 0; b<cred.length; b++){
to += "(" + grade[b] + " x " + cred[b] + ") + ";}
... .getElementById('').innerHTML = to;
Expecting output with cred = [10, 20], grade = [11, 21]:
(10 x 11) + (20 x 21) <-- this expands when arrays have values added to them.
Actual output:
(undefined) <-- doesn't change
I don't have jquery running on my coding platform so javascript code would be really great :)
To do a list of numbered steps, you want to use the ol tag.
Obviously, you'll want to populate the ol tag with li tags :P
Have you tried a simplified version to see if it works? Something like this:
document.getElementById("bdown").innerHTML=to;

Categories