Javascript median using for - javascript

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.

Related

Show full ArrayList in HTML

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

Better way to slice up a string?

I'm trying to take a string with blank spaces and display each word line-by-line in console output.
My javascript code takes a string and creates an array of indexes where spaces are identified using an indexOf() operation. This is then passed through a slice loop which subtracts the different indexes to get a length of the string to slice and the space index to locate it in the existing string. The output is the final console.log and it appears to do what I need it to even when passing in random strings.
var sp = " ";
var myStr = "I am a \"double quoted\" string inside \"double quotes\""
var twoStr = 'I am a string "and I am a string"';
var stringadd = "and I can slice whenever I want."
var threeStr = myStr + sp + twoStr;
var fourStr = threeStr + sp + stringadd;
console.log("string length = ", fourStr.length);
var i = 0;
var n = 0;
var sentence = [i];
for (n = 0; n < fourStr.length; n++) {
var pos = fourStr.indexOf(sp, n) //find the index of the space
if (n == pos) {
sentence[i] = pos; //place the index in an array
i++;
} else(i);
}
var arraysent = fourStr.split(sp); //test split function for string
console.log("Array Sentence:\n", arraysent)
console.log("space index length:\n", sentence.length) //check array length
console.log("space index array:\n", sentence) //display array with "space" indexes
console.log("sliced string:\n", fourStr.slice(sentence[0] - 1, sentence[0])); //display first index
var j = 0;
for (j = 0; j < sentence.length; j++) {
var slicesent = fourStr.slice(sentence[j], sentence[j + 1]); //automate remaining index display
console.log(slicesent);
}
I was hoping to find an easier/simpler way to do this same task since passing the string to the array is not efficient and re-creates the string a bunch of times. Could someone please explain a better alternative that will show the individual words of a string line-by-line in the console?
Thank you
This is literally done by String.split()
function logWordsBySpaces(str){
let arr = str.split(" ");
arr.forEach(function(a){ console.log(a); })
}
logWordsBySpaces("Karma karma karma karma karma chameleon!")
You should use .split
var sp = " ";
var myStr = "I am a \"double quoted\" string inside \"double quotes\""
var twoStr = 'I am a string "and I am a string"';
var stringadd = "and I can slice whenever I want."
var threeStr = myStr + sp + twoStr;
var fourStr = threeStr + sp + stringadd;
const result = [myStr, twoStr, stringadd, threeStr, fourStr].map(string => string.split(sp));
console.log(result);

Check how many times a string is inside a string

I got this string:
var longText="This is a superuser test, super user is is super important!";
I want to know how many times the string "su" is in longText and the position of each "su".
I was trying with:
var nr4 = longText.replace("su", "").length;
And the difference of lenght between the main text and the nr4 divided by "su" lenght beeing 2 is resulting a number of repetitions but i bet there is a better way of doing it.
For example
var parts=longText.split("su");
alert(parts.length-1); // length will be two if there is one "su"
More details using exec
FIDDLE
var re =/su/g, pos=[];
while ((result = re.exec(longText)) !== null) {
pos.push(result.index);
}
if (pos.length>0) alert(pos.length+" found at "+pos.join(","));
Use exec. Example amended from the MDN code. len contains the number of times su appears.
var myRe = /su/g;
var str = "This is a superuser test, super user is is super important!";
var myArray, len = 0;
while ((myArray = myRe.exec(str)) !== null) {
len++;
var msg = "Found " + myArray[0] + ". ";
msg += "Next match starts at " + myRe.lastIndex;
console.log(msg, len);
}
// "Found su. Next match starts at 12" 1
// "Found su. Next match starts at 28" 2
// "Found su. Next match starts at 45" 3
DEMO
Could do :
var indexesOf = function(baseString, strToMatch){
var baseStr = new String(baseString);
var wordLen = strToMatch.length;
var listSu = [];
// Number of strToMatch occurences
var nb = baseStr.split(strToMatch).length - 1;
for (var i = 0, len = nb; i < len; i++){
var ioF = baseStr.indexOf(strToMatch);
baseStr = baseStr.slice(ioF + wordLen, baseStr.length);
if (i > 0){
ioF = ioF + listSu[i-1] + wordLen;
}
listSu.push(ioF);
}
return listSu;
}
indexesOf("This is a superuser test, super user is is super important!","su");
return [10, 26, 43]
var longText="This is a superuser test, super user is is super important!";
var count = 0;
while(longText.indexOf("su") != -1) { // NB the indexOf() method is case sensitive!
longText = longText.replace("su",""); //replace first occurence of 'su' with a void string
count++;
}

Adding a comma at every third number character

In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo

Unicode value \uXXXX to Character in Javascript

I've never done this before and am not sure why it's outputting the infamous � encoding character. Any ideas on how to output characters as they should (ASCII+Unicode)? I think \u0041-\u005A should print A-Z in UTF-8, which Firefox is reporting is the page encoding.
var c = new Array("F","E","D","C","B","A",9,8,7,6,5,4,3,2,1,0);
var n = 0;
var d = "";
var o = "";
for (var i=16;i--;){
for (var j=16;j--;){
for (var k=16;k--;){
for (var l=16;l--;){
d = c[i].toString()
+ c[j].toString()
+ c[k].toString()
+ c[l].toString();
o += ( ++n + ": "
+ d + " = "
+ String.fromCharCode("\\u" + d)
+ "\n<br />" );
if(n>=500){i=j=k=l=0;} // stop early
}
}
}
}
document.write(o);
The .fromCharCode() function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.
You could ammend your code to make a string (without the '\u') from your hex number, and call
var n = parseInt(hexString, 16);
to get the value. Then you could call .fromCharCode() with that value.
A useful snippet for replacing all unicode-encoded special characters in a text is:
var rawText = unicodeEncodedText.replace(
/\\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
Using replace, fromCharCode and parseInt
If you want to use the \unnnn syntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:
var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
var hi = i >> 4;
var lo = i % 16;
var code = "'\\u00" + hex[hi] + hex[lo] + "'";
var char = eval(code);
s += char;
}
document.write(s);
Of course, just using String.fromCharCode(i) would be a lot easier...

Categories