This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 4 months ago.
Can anyone help me to find the error? My main target is when we enter an array to give the result same as the below I showed, Input
{-5, -4, 10, 12, 13, 4, 5, -8, -6}
output
{10, 12, 13, 4, 5, -5, -4, -8, -6}
Here I attached my full code. I don't get outputs.
function foo() {
var arrch = document.getElementById("text").value.spilt(" ").map(Number);
var dlina = arrch.length;
var new_arr = [];
var new_arr2 = [];
var k = 0;
var summa = 0;
var n = 0;
for (var i = 0; i < dlina; i++) {
if (arrch[i] > 0) {
summa += arrch[i];
new_arr[n] = arrch[i];
n++;
} else if (arrch[i] < 0) {
new_arr2[k] = arrch[i];
k++;
}
}
new_arr = new_arr.join(" ");
new_arr2 = new_arr2.join(" ");
document.getElementById("text2").innerHTML = new_arr + " " + new_arr2;
document.getElementById("text3").innerHTML = summa;
}
<H3>RK1</H3>
<form>
<p>Enter Array</p>
<input type="text" id="text" placeholder="Enter Text"><br>
<p>Changed array</p>
<p id="text2"></p>
<p>plus Array</p>
<p id="text3"></p>
<button onclick="foo()">Give Answer</button>
</form>
If you just want to sort the negative numbers to the end of the array, you can sort based on the sign of the numbers. You can sum the array using reduce:
const arr = [-5,-4,10,12,13,4,5,-8,-6]
arr.sort((a, b) => Math.sign(b) - Math.sign(a))
console.log(arr)
const sum = arr.reduce((acc, el) => acc + el)
console.log(sum)
Here's a modified version of your code with those changes (and the typo in split noted by #EricFortis corrected):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--
Positive Numbers one side and negetive numbers other side
-->
<title>RK1</title>
</head>
<body>
<H3>RK1</H3>
<form>
<p>Enter Array</p>
<input type="text" id="text" placeholder="Enter Text"><br>
<p>Changed array</p>
<p id="text2"></p>
<p>plus Array</p>
<p id="text3"></p>
<button onclick="foo(event)">Give Answer</button>
</form>
<script type="text/javascript">
function foo(e) {
e.preventDefault();
var arrch = document.getElementById("text").value.split(" ").map(Number);
arrch.sort((a, b) => Math.sign(b) - Math.sign(a))
var summa = arrch.reduce((acc, el) => acc + el)
document.getElementById("text2").innerText = arrch;
document.getElementById("text3").innerText = summa;
}
</script>
</body>
</html>
you can code that this way...
const myForm = document.querySelector('#my-form')
myForm.onsubmit = e =>
{
e.preventDefault()
let res = myForm.txtNums.value
.match(/([-+]?\d+)/g).map(Number)
.reduce((r,n) =>
{
r[(n<0?'neg':'pos')].push(n)
r.sum += n
return r
}
,{sum:0,pos:[],neg:[]}
)
myForm.txtOut_1.textContent = `{${res.pos.concat(res.neg).join(',')}}`
myForm.txtOut_2.textContent = res.sum
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
}
label {
display : block;
font-size : .8rem;
padding : .4rem .2rem;
}
input,
output {
display : block;
border : 1px solid lightslategrey;
width : 16rem;
font-size : 1rem;
padding : .2rem .4em;
}
<form id="my-form">
<label>Enter Array
<input type="text" name="txtNums"
placeholder="Enter Text"
value="{-5,-4,10,12,13,4,5,-8,-6}">
</label>
<label>Changed array
<output name="txtOut_1">.</output>
</label>
<label>plus Array
<output name="txtOut_2">.</output>
</label>
<button>Give Answer</button>
</form>
Related
I wrote this code to display a table of random numbers between two values using vanilla JavaScript, I used an array to store the random values, and then I displayed them on the page using tales. and I want to count the number of occurrences of every number in this table and display that number. I tried to use a for loop but it didn't work.
Can anybody help?
//Variables Exercice 3
var dim = document.getElementById("dimensions");
var min = document.getElementById("min");
var max = document.getElementById("max");
var table = document.getElementById("table");
var btn = document.getElementById("btn");
//Function Exercice 3
btn.addEventListener("click", generate);
function generate() {
if (dim.value == "" || min.value == "" || max.value == "") {
alert("Merci de remplir tous les champs");
} else if (
Number(min.value) > Number(max.value) ||
Number(min.value) == Number(max.value)
) {
alert("La valeur minimale doit être inférieur à la valeur maximale");
} else {
for (var j = 0; j < Math.floor(dim.value / 10); j++) {
var row = document.createElement("tr");
for (var i = 0; i < 10; i++) {
var arr = [];
var cell = document.createElement("td");
while (arr.length < dim.value) {
var r = Math.floor(
Math.random() * (Number(max.value) - Number(min.value)) +
Number(min.value)
);
arr.push(r);
}
table.append(row);
row.append(cell);
cell.innerHTML = arr[i];
}
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Examen 4 JavaScript</title>
</head>
<body>
<div class="Ex1">
<form>
<h1>Exercice 3</h1>
<div class="container">
<div class="dimensions">
<label for="dimensions">Dimension du tableau</label>
<input type="text" name="dimensions" id="dimensions" pattern="[0-9]+" title="Merci de fournir que des numéros" />
</div>
<div class="min">
<label for="min">La valeur minimale</label>
<input type="text" name="min" id="min" pattern="[0-9]+" title="Merci de fournir que des numéros" />
</div>
<div class="max">
<label for="max">La valeur maximale</label>
<input type="text" name="max" id="max" pattern="[0-9]+" title="Merci de fournir que des numéros" />
</div>
</div>
<button type="button" id="btn">Générez un tableau</button>
<table id="table"></table>
</form>
</div>
<script src="main.js"></script>
</body>
</html>
The problem is you're trying to generate your random numbers at the same time that you're building your table. In programming, it's generally easier to break your process into individual steps and do them one at a time.
So your program could be:
Generate random numbers.
Count the frequency of the numbers.
Build the table.
// Sample list of numbers.
const numbers = [1, 1, 4, 1, 6, 3, 1, 5, 4, 2, 2, 2, 2];
// Array.prototype.reduce iterates over an array
// and turns it into something else, called the accumulator.
const frequency = numbers.reduce((acc, item) => {
// This tertiary statement says to add one to whatever
// is at acc[item] if it exists, or just set acc[item] to one.
acc[item] = acc[item] ? acc[item] + 1 : 1;
return acc;
}, {});
console.log(frequency);
const table = document.querySelector("table");
let i = 0;
for (let rowIndex = 0; rowIndex <= Math.floor(numbers.length / 10); rowIndex++) {
const row = document.createElement("tr");
for (let cellIndex = 0; cellIndex < 10; cellIndex++) {
const cell = document.createElement("td");
cell.innerText = numbers[i];
const sub = document.createElement("sub");
sub.innerText = frequency[numbers[i]];
cell.append(sub);
row.append(cell);
i++;
if (i >= numbers.length) {
break;
}
}
table.append(row);
}
<table></table>
It doesn't matter if the numbers are type string or type number, so long as all are the same. You could populate the numbers array with the result of a querySelectorAll from the table, or from the arr variable you're setting in your loop.
I just wrote this in order to take n from user and also n names , and then print them on screen after clicking on button , but i cant initialize my array ...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
var n;
var i =0;
var names = [];
function mf1(){
n=parseInt(document.getElementById("n").value);
}
function mf2(){
if (i<n){
names[i]=document.getElementById("nam").value;
i++;
document.getElementById("rem").innerHTML=names[i];
}
}
</script>
inset n : <input type="text" id="n"> <button onClick="mf1()">take n</button>
insert name: <input type="text" id="nam"> <button onClick="mf2()"> take name</button>
<p id="rem"></p>
</body>
</html>
The problem is that in function mf2 you can't access names[i] because you increment i++ before.
var n;
var i = 0;
var names = [];
var input1 = document.getElementById("n");
var input2 = document.getElementById("nam");
function mf1(){
n = parseInt(input1.value);
console.log(n);
}
function mf2(){
if (i < n){
names[i] = input2.value;
console.log(names);
document.getElementById("rem").textContent = names[i];
i++;
}
}
To count the characters typed in textarea, I have a code that can count with space between words. But I want both the functionalities like to count with words with space and without space in Simple JavaScript.
Since I am not a programming expert, I could not try other methods or frameworks. I prefer Native JavaScript code.
Current JavaScript Code to count Characters with Space:
function countChars(obj){
document.getElementById("charNum").innerHTML = obj.value.length+'
characters';
HTML
<form name="post" method="POST">
<textarea name="new" charset="utf-8" onKeyDown="toggleKBMode(event)" value="copyThisContent" id="newInputID" onKeyPress="javascript:convertThis(event)" style="height:255px; Width:100%; margin-top: -17px; line-height: 15px;" placeholder="Write something.."" onkeyup="countChars(this);"></textarea>
<p id="charNum">0 characters</p>
</form>
Kindly help me to modify the above code for counting characters in textarea with space and without space. If possible I'm expecting Word count functionality as well.
I am expecting functionalities that is already existing in the following websites. https://easywordcount.com or https://wordcounter.net/
function WordCount() {
var wordCounterwithSpace = 0;
var wordCounterwithoutSpace = 0;
var val = document.getElementById('textAreaId').value;
for (var i = 0; i < val.length; i++) {
if (val[i] == ' ') {
wordCounterwithSpace++;
continue;
} else {
wordCounterwithoutSpace++;
wordCounterwithSpace++;
}
}
console.log('With Spaces :', wordCounterwithSpace);
console.log('Without Spaces :', wordCounterwithoutSpace);
}
Check this below code snippet:
function countChars() {
var val = document.getElementById("newInputID").value;
var withSpace = val.length;
// Without using regex
//var withOutSpace = document.getElementById("newInputID").value.split(' ').join('').length;
//with using Regex
var withOutSpace = val.replace(/\s+/g, '').length;
var wordsCount = val.match(/\S+/g).length;
document.getElementById("wordCount").innerHTML = wordsCount + ' words';
document.getElementById("charNumWithSpace").innerHTML = 'With space: ' + withSpace + ' characters';
document.getElementById("charNumWithOutSpace").innerHTML = 'Without space: ' + withOutSpace + ' characters';
}
<html>
<body>
<textarea name="new" charset="utf-8" id="newInputID" style="height:100px; Width:100%; line-height: 15px;" placeholder="Write something.." onkeyup="countChars()"></textarea>
<p id="wordCount">0 Words</p>
<p id="charNumWithSpace">0 characters</p>
<p id="charNumWithOutSpace">0 characters</p>
</body>
</html>
use regex
function countChars(obj){
var valLength=obj.value.replace(/\s/g,'').length;
document.getElementById("charNum").innerHTML = valLength+'
characters';}
function countChars(obj){
const words = obj.value.split(' ');
words.length // word count
console.log('word count is ', words.length)
const noSpaceString = obj.value.split(' ').join('');
noSpaceString.length // string length with no space
console.log('all characters without whits space ', noSpaceString.length)
}
Did you look good before asking your question?
look at this, it may be able to help you :
Show how many characters remaining in a HTML text box using JavaScript
But if you wish to do more simple look below :
html :
<textarea id="field"></textarea>
<div id="charNum"></div>
javascript:
$("#field").keyup(function(){
el = $(this);
if(el.val().length >= 11){
el.val( el.val().substr(0, 11) );
} else {
$("#charNum").text(el.val().length + '/ 10' );
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!DOCTYPE html>
<html>
<body style="text-align: center">
<textarea
id="txtarea"
oninput="wordCount()"
rows="8"
cols="45"
placeholder="Enter text ....."
></textarea>
<label>Total Word Count:</label>
<label id="showCount"></label>
<script>
function wordCount() {
var text = document.getElementById("txtarea").value;
var count = 0;
var text = text.replace(/(\r\n|\n|\r)/gm, " ");
var text = text.replace(
/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,
""
);
var text = text.replace(/[^a-zA-Z0-9]/g, " ");
// var text = text.replace(/[^a-zA-Z ]/g, " ");
var split = text.split(" ");
for (var i = 0; i < split.length; i++) {
// text.trim().split(/\s+/).length;
if (split[i] != "") {
count++;
}
}
document.getElementById("showCount").innerHTML = count;
}
</script>
</body>
</html>
<script></script>
</body>
</html>
I want to make a program which can sum up all the digits in a given number. I want my script to return the resul on click of the button Please help me find error in my code. Thanks
<!doctype html>
<html>
<head>
<script type="text/javascript">
function sumdigits()
{
var num=document.getElementById("a").value;
var len=num.length();
alert(len);
if(len!=0)
{
var sum=0;
var ldigit=0;
while(num!=0)
{
ldigit=num%10;
sum+=ldigit;
num/=10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number="+sum;
}
</script>
</head>
<body>
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</body>
</html>
DEMO
onClick should be onclick, length() should be length and sum not out of scope
function sumdigits(){
var num = document.getElementById("a").value;
var len = num.length; // note "length"
var sum; // "sum" scope
alert(len);
if(len!==0){
sum = 0;
var ldigit=0;
while(num!==0){
ldigit=num%10;
sum += ldigit;
num /= 10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number = "+ sum;
}
This is how to make it work, now, I don't know what math you're trying to apply in there and what's it's purpose...
The main reason the script is breaking is because you are calling length() on num variable instead of num.length. Below is a link to a working fiddle with that and a few other adjustments made ( check to see if the value's are integers etc...).
http://jsbin.com/uBAyOJep/1/
<!doctype html>
<html>
<head>
</head>
<body>
<form onsubmit="sumdigits()">
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</form>
</body>
</html>
function sumdigits()
{
var sum = 0,
num = document.getElementById("a").value,
len = num.length,
result = document.getElementById("result");
if( len !== 0 ){
for( var i = 0; i < len; i++){
var lineValue = parseInt(num[i], 0);
if ( !isNaN(lineValue) ) {
sum += lineValue;
}
}
}
result.innerHTML="Sum of digits of the given numbers = " + sum;
}
I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0