Arrays checking matched items - javascript

Please I have two arrays
Var subject("goat","man");
Var predicate ("enter", "come");
I want to make a search page that will display the results if the input items matches the two arrays
Please help

var subject = ['goat','man'];
var predicate = ['enter', 'come'];
var i;
function my_func(){
var search_value = document.getElementById('search1').value; //the entered value in the searchbox
for(i = 0; i < subject.length && predicate.length; i++){ //Find the item that you enter in searchbox
if(search_value === subject[i]){ //
document.getElementById('demo').innerHTML = subject[i];
}
if(search_value === predicate[i]){
document.getElementById('demo').innerHTML = predicate[i];
}
}
}
<input type="search" id="search1"> <button onclick = "my_func()">Show</button>
<p id="demo"></p>

Related

how do i sum all array arguments

I want to have a webpage with one input box and two button. first button for adding input box value to my array and the second to sum all array values. but it return 0 :(
<input type="text" placeholder="Enter number" id="input">
<button id="add">Add to Array</button>
<button id="sum">Sum All</button>
<p id="text"></p>
<script>
var myArr = []; //contain numbers that i've inputed
var input = document.getElementById('input');
var addBtn = document.getElementById('add');
var sumBtn = document.getElementById('sum');
addBtn.onclick = function () {
myArr.push(input.value);
input.value = "";
}
function sumAll() {
var i , sum = 0;
for ( i in myArr.length ) {
sum += i;
}
return sum;
}
sumBtn.onclick = function(){
var paragraph = document.getElementById('text');
var a = sumAll();
paragraph.innerHTML = a;
}
</script>
You can use the for-of syntax to loop thru your array.
function sumAll() {
var i , sum = 0;
for ( i of myArr ) {
sum += Number(i);
}
return sum;
}
You need to run your for loop properly:
When you say for ( i in myArr.length ) {the value of i comes out as undefined so the summation never happens. You should use debugging to figure out such issues.
function sumAll() {
var i, sum = 0;
for (i = 0; i < myArr.length;i++) {
sum += +myArr[i];
}
return sum;
}
Notice +myArr[i];that uses unary operator +. This can attempt to convert the string in the input field to number(both int and floats).
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators
This should be way to go..
1.You have to use parseInt to treat values as ints
2.Loop correctly over array
<script>
var myArr = []; //contain numbers that i've inputed
var input = document.getElementById('input');
var addBtn = document.getElementById('add');
var sumBtn = document.getElementById('sum');
addBtn.onclick = function () {
myArr.push(input.value);
input.value = "";
}
function sumAll() {
var i , sum = 0;
for ( i in myArr ) {
sum += parseInt(myArr[i]);
}
return sum;
}
sumBtn.onclick = function(){
var paragraph = document.getElementById('text');
var a = sumAll();
paragraph.innerHTML = a;
}
</script>

Form value always read as undefined in Javascript

I'm a new self taught programmer working on my first homework assignment, so I apologize if my naming convention is off. This is the most bizarre thing. No matter how I request the input value, (hoping to pull a number) it always reads as undefined.
Everything works in my javascript function except pulling the input value. I have used forms in the past, and the variables appear to be referencing it fine; I have tried both document.formName.inputName.value, as well as document.getElementById ('input-id').value and it returns undefined. I have renamed my form and variables so many times to see if that was the issue and stI'll nothing. I have tried both input type text and number, and stI'll undefined.
Am I missing something due to how new I am? Please help. Links to github and jsfiddle below.
https://github.com/MissElle/calculator?files=1
https://jsfiddle.net/MissElle/qf7xL8gj/
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff', '#ffbfbf', '#ffd299', '#ffffff', '#000000'];
function calcData(element) {
if(typeof element === 'number') {
console.log(element);
subCount.push(element);
var starDiv = document.createElement('div');
starDiv.className = 'star';
var starHolder = document.getElementById('star-holder');
starHolder.appendChild(starDiv);
starDiv.style.background = 'radial-gradient(circle, ' + starColors[Math.floor(Math.random() * starColors.length)] + ', transparent, transparent)';
numCount.innerHTML = subCount.length;
for(var i in subCount) {
subSum += subCount[i];
numSum.innerHTML = subSum;
var subMean = subSum/subCount.length;
numMean.innerHTML = subMean;
}
}else {
numCount.innerHTML = 'Not a Number';
console.log(element);
}
subSum = 0;
event.preventDefault();
}
function clearData() {
subCount = [];
subSum = 0;
subMean = 0;
numSum.innerHTML = '';
numMean.innerHTML = '';
numCount.innerHTML = '';
var starHolder = document.getElementById('star-holder');
var starDiv = starHolder.getElementsByClassName('star');
while(starDiv.length > 0) {
starHolder.removeChild(starDiv[0]);
}
}
<form name="compute" onsubmit="calcData()" onReset="clearData()">
<p class="bold">Please enter a number</p>
<input type="number" name="calculate" id="calculation" step="any"><br>
<input type="submit" name="submit" value="star">
<input type="reset" value="nostar" name="clearForm">
<div class="row">
<div class="typevalue"><h4>Count:</h4><h4>Sum:</h4><h4>Mean:</h4></div>
<div class="numbervalue"><p id="count"></p><p id="sum"></p><p id="mean"></p></div>
</div>
</form>
Move your variable declarations inside your function like this:
function calcData(element) {
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff',
'#ffbfbf', '#ffd299', '#ffffff', '#000000'];
...
If you declare your dataInput outside the function you get no value because that JS code is run after the page loads (before your user types any number in your function).
You have to declare it inside your function that way you get the value of your input when the user clicks on the button.

Javascript Higher Order Functions and DOM

I am working on a project that takes text that a user inputs in a text box and returns the most common word.
Javascript:
var bestMode = 1;
var currentMode = 0;
var character;
function Find_Word(){
var words = document.getElementById('words').innerText;
var punctuationless = words.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var WordList = finalString.split(" ");
return FindMode(WordList);
}
function FindMode(WordList){
for(var i=0; i<WordList.length; i++){
for(var m=i; m<WordList.length; m++){
if(WordList[i] == WordList[m]){
currentMode += 1;
}
if(bestMode<currentMode){
bestMode = currentMode;
character = WordList[i];
}
}
currentMode = 0;
}
}
console.log(bestMode);
HTML:
<html>
<body>
<h1>Most common word used</h1>
<input type="text" id="words" rows="10" columns="30"></input>
<button type="button" id="FindWord" onclick="Find_Word()">Find Word</button>
<script src="CommonWord.js"> </script>
</body>
</html>
What I can't figure out is the correct way to pull text from the text box into a variable as one string. My function Find_Word takes the received string when the button is pressed and strips away punctuation and leaves an array WordList with with each individual word in the string.
After that, I also can't understand how to pass that array into my second function findMode where I iterate through each value of the array to find the most common word. That is saved in the variable bestMode.
It looks as if you are both getting the current text and passing the array correctly (although perhaps you should get the textbox value using the .value property). What problem are you having exactly? I am not sure what FindMode is supposed to do either.
Here is some script that is based on what you posted that sorts "words" according to how often they appear :
(function(w) {
w.Sort_Words = function(words) {
var o = {}, l = [];
for(var i=0; i<words.length; i++) {
if (typeof o[words[i]] === 'undefined') {
o[words[i]] = 0;
l.push(words[i]);
}
o[words[i]] ++;
}
l.sort(function(a, b) { return o[b] - o[a]; });
return l;
};
w.Find_Word = function() {
var text = document.getElementById('words').value;
var words = text.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"").replace(/\s{2,}/g," ").split(' ');
var sorted = w.Sort_Words(words);
document.getElementById('results').innerText = sorted.length === 0 ?
'You must type at least one word' :
'The most commonly used word was: ' + sorted[0];
};
})(window);
Fiddler: http://jsfiddle.net/4u1mv20h/4/

Can't figure out how to find the primes

I have a program that is supposed to take two numbers entered by the user and send them to a function. This function will be used to determine all the prime numbers between those two numbers. However, I just can't seem to figure out how to find all the primes. I created an array that should hold all numbers between the two user submitted ones. But I don't know how to iterate through it and place all the prime numbers found into a new array. I know it's basic stuff, but for some reason I just can't figure it out.
Here's the code for my function so far.
function displayPrimeNumbers(p1, p2) {
var numbers = [];
var primes = [];
for(i = p2; i == p1; i++){
numbers.push(i);
for(i = 0; i < numbers.length; ++i){
if () {
}
}
}
}
<html>
<head>
<script = "text/javascript>
function prime(num1,num2)
{
var s="";
var count=0;
for(i=parseInt(num1);i<num2;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
count ++ ;
}
}
if(count == 0)
{
s=s+"\n"+i;
}
count = 0;
}
document.getElementById('textarea1').value = s;
}
</script>
</head>
<body>
<input type = "text" id = "num1">
<input type = "text" id = "num2">
<input type = "button" value = "Click here" onclick = "prime(document.getElementById('num1').value,document.getElementById('num2').value)"><br>
<textarea id = "textarea1" rows="10" cols = "20">answer</textarea>
</body>
</html>

Create 2 arrays

I need to create 2 arrays in JS from an input value. The first should contain all my inputs values and the second one should contain all my inputs values but for the last one.
I tried this but it doesn't work.
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
var comp = [];
function clickHandler()
{
n = input.value;
for (var i =0; i < 10; i++)
{
valori.push(parseInt(n));
comp = valori.pop();
console.log(valori);
console.log(comp);
break;
}
}
</script>
</body>
The ideea is that I want to check if an input value has been entered before. I thought of doing that by creating 2 arrays like I mentioned before and then compare "n" to the "comp" array
if you are just to check element exist or not.. why dont u why indexOf(n)??
no need to create two array and for loop etc etc.. just indexOf will work for you..
check the below code..
<html>
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
function clickHandler()
{
if(isNaN(input.value))
{
alert('value is not a Number');
}
else
{
var nbr = parseInt(input.value);
if(valori.indexOf(nbr) < 0)
{
valori.push(nbr);
input.value="";
}
else
{
alert('element already exists.');
}
}
}
</script>
</body>
</html>
U are setting value on comp which is array u need to set value at index .
function clickHandler()
{
var is = true;
var n = parseInt(document.getElementById("inp").value);
if(!isNaN(n))
{
for (var i =0; i < valori.length; i++)
{
if(n === valori[i])
{
console.log("duplicate");
is = false;
break;
}
}
if(is)
valori.push(n);
}
console.log(valori);
}
DEMO

Categories

Resources