Searching for number inside of an array - javascript

Forgive me, I am not quite skilled and fairly new to the language and programming practices. I am creating a button which prompts the user to enter a number once the number is entered, I create a for loop that iterates through the same amount as the number. For example, the user enters 4 and the screen will display 0 1 2 3 and then I have a button that asks the user to enter a number to see if that number exists in the previous array. So if the user entered 3 it would dispay "it exists" if they entered 5 it would display "number not found". Should I create an array to store the iterations and then run that array through a function that searches for the number. Looking for guidance, thank you for the help guys.
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var sn = parseInt(prompt("Search for number"),10);
for(var j = 0; j < sn; j++){
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>

Make your n variable global
Than compare if sn is higher than n
var n; // Make it global
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
n = parseInt(prompt("Please enter a number"), 10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for (var i = 0; i < n; i++) {
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber() {
var sn = parseInt(prompt("Search for number"), 10);
var isHigher = sn > n; // n is now accessible in this function
var message = isHigher ? "Not found" : "Number found!";
alert( message );
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick="findNumber()">Click!</button>

To search an array, use the indexOf() method of a JavaScript array. The original post gives an example populating the array with myArray[x]=x, creating options pointed out by other solutions. Presuming you want to search a more general case of an array, you could use indexOf directly or define a function that returns true or false:
function inArray(myArray, queryValue) {
return myArray.indexOf(queryValue) > -1;
};
Arrays in JavaScript are objects with some additional methods like pop(), indexOf(), etc. JavaScript objects are associative arrays; this solution only applies to Array objects. Array objects are constructed with the [] literal or the Array() constructor. Arrays can only have properties named by ints, unlike other JavaScript associative arrays. See Eloquent JavaScript.

In this theoretic example, it's true that you only need to check if the second number entered is smaller than the first number. If you want to search for a number in an array of any numbers, you can use the javascript indexOf function. See example below:
var arr = [1,6,77,888];
if (arr.indexOf(66) > -1) {
alert('number is in array');
} else {
alert('number is not in array');
}

There are a couple of ways to do this. For the sake of simplicity, I'll use a global variable here.
// A global variable to store user input
var userInput;
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Store the user's input to our global variable
userInput = n;
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var el = document.getElementById("result");
var sn = parseInt(prompt("Search for number"),10);
// If number is within the range
if (sn < userInput) {
el.textContent = "it exists";
}
// If number is not within the range
else {
el.textContent = "number not found";
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
<p id="result"></p>

Related

Adding splitted values in loops

I suggest u look at this picture, and then u look at the code I have written:
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
for(i = 0; i <= splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
}
I am taking the value from the box which says "Enter list of numbers and/or words" and I am splitting it. I split it so I have all the numbers like this "1 2 3" and so I can add them. I use the for loop for that. The for loop goes through every number and then it adds it. But when I press the button, it shows me undefined.
Why am I getting undefined?
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
//make sure that the values are in a number format
document.getElementById("resultNumberTotal").value = splitted.reduce(function(a, b) {return Number(a) + Number(b);}, 0)
}
for the best practice make sure that allow number only for the input fields :) good luck
You need to somehow add the numbers up, either using the += operator, or by using something like .reduce() as I have done below.
function addNumbers() {
var val = document.getElementById("listInput").value;
document.getElementById("resultNumberTotal").value = val.split(" ").reduce(function(runningTotal, currentArrayElement) {
// make sure the value they typed is a number
// if not, fail gracefully and simply ignore it
if (!isNaN(Number(currentArrayElement))) {
// if it is a number, add it to the running total
runningTotal+= Number(currentArrayElement);
}
return runningTotal; // return the running total
}, 0); // start with 0 as the initial value for runningTotal
}
<input type="text" id="listInput" placeholder="insert values here..." style="width: 300px;" />
<button onclick="addNumbers()">Add Numbers</button>
<br/>
<br/>
<hr/>
Number Total: <input id="resultNumberTotal"/>
You are getting undefined, because you are displaying the value of the last element of the array and not doing the Sum as you mentioned in the question.
Following code always overrides the value of resultNumberTotal by the value of splitted[i]. Since, your for loop iterates for i <= splitted.length it reaches the index which doesn't exist in the array, when you get a property which doesn't exist on an object, you get undefined
for(i = 0; i < splitted.length; i+=1) {
document.getElementById("resultNumberTotal").value = splitted[i];
}
So, for doing the sum, you need to make the code like
function addNumbers() {
var splitted = document.getElementById("listInput").value.split(" ");
var total = 0;
for(i = 0; i < splitted.length; i++) {
var numberValue = +splitted[i];
if(!isNaN(numberValue)){
total = total + numberValue ;
}
}
document.getElementById("resultNumberTotal").value = total;
}

Multiplication table in JavaScript returns undefined with multiplication number WHY?

Script part:
function makeTable() {
var num = document.getElementById('Numb').value;
var myPara = document.getElementById('para');
var tb = new Array();
for (var i = 1; i <= 10; ++i) {
var result = num * i;
tb.push(result);
tb[i] = tb[i] + "<br>";
}
tb = tb.join("");
myPara.innerHTML = tb;
}
HTML part
<input type = "number" value = "" id = "Numb" placeholder = "TABLE NUMBER">
<input type = "button" value = "Give me Table" onClick = "makeTable()">
<p align = "center" name = "myownpara" id = "para"> </p>
When I run this code it returns undefined with first element of array
Arrays start at 0, not 1. Change it to var i= 0 in your 'for' loop and add the line if(i==0) continue; right after starting your for loop to skip over 0.
Actually, another problem is your array. It might be best to initialise your 0th element because you are looking at it later. Change new Array() to new Array(""): To already add a 0th element so you dont have to when you use my aforementioned continue statement.
Update, refinement
I refined your code below. I don't know why you are using an array, as you want to output a string anyway. So Just add it to the string for every element as it reduces the amount of things you need to do. The below will work. I also removed you 'myPara' as you only use it once anyway, so theres no point in saving it.
Also note that in this case we don't need to start at 0 as we don't have an array to add to.
function makeTable() {
var num = document.getElementById('Numb').value;
// lets use a string since thats what you want in the end and its easier.
var tb = "";
for (var i = 1; i <= 10; ++i) {
// add it to the string. I reduced the number of steps as its so simple
// You don't need to save stuff in vars for this thing.
tb += (num * i) + "<br>";
}
document.getElementById('para') = tb;
}

Text Analysis webpage does not work

For a homework assignment, I have to make a web page that has a text area. The user inputs some text, hits the analyse button, and the output is supposed to be a list of the frequency of words of a given number of characters. For example, "one two three" would be two words of three characters and one word of five characters. The text area works fine, but I can"t seem to get the output to appear.
Here is the html:
<body>
<textarea id="text" rows="26" cols="80"></textarea>
<form>
<input type="button" id="analyse" value="Analyse Text">
</form>
<div id="output"></div>
</body>
The JavaScript file has 6 functions. The first function returns an array that stores the number of characters for each word in the input textarea:
function getWordInfo() {
var text = document.getElementById("text").value;
//the variable wordArray uses a regular expression to parse the input
var wordArray = text.split("/\w\w+/g");
var arrayLength = wordArray.length;
var charArray = [];
for (var i = 0; i < arrayLength; i++) {
var splitWord = wordArray[i].split("");
var wordLength = splitWord.length;
charArray.push(wordLength);
}
return charArray;
}
The second function is a simple object constructor that has a name property and a count property. The count property has a default value of 0.
function obCon(name,count) { //object constructor
this.name = name;
this.count = count;
count = typeof count !== "undefined" ? count : 0;
}
The third function returns an array that stores word objects. Each object has a name property and a count property. The name property is the number of characters in a word. The count property counts how many times an object with a given name property appears.
function arCon() { //array constructor
var charNum = getWordInfo();
var arrayLength = charNum.length;
var obArr = [];
for (var i = 0; i < arrayLength; i++) {
if (typeof obArr.indexOf( newOb.name === charNum[i] ) != "undefined" ) { // checks if the object needed exists
obArr.indexOf( newOb.name === charNum[i] ).count = obArr.indexOf( newOb.name === charNum[i] ).count + 1;
}else{
var newOb = new obCon(charNum[i]);
newOb.count = newOb.count + 1;
obArr.push(newOb);
}
}
return obArr;
}
The fourth function is a string formatter, meant format the objects from arCon into a single readable string, then store it in an array.
function formatter() {
var strAr = arCon();
var arrayLength = strAr.length;
var formatStr = [];
for (var i = 0; i < arrayLength; i++) {
var str = "Number of characters: " + strAr[i].name + ", Number of words with this length: " + strAr[i].count;
formatStr.push(str);
}
return formatStr;
}
The fifth function is called for an event handler, meant to handle the click of the analyse button. On click, it is meant to get the div tag, get the formatted array, then loop though each element in the array, where it creates a p element element, pulls the formatted string, sets the p element value to the formatted string, then appends the p element to the div tag.
function analyseButtonClick() {
var div = document.getElementById("output");
var str = formatter();
var arrayLength = str.length;
for (var i = 0; i < arrayLength; i++) {
var par = document.createElement("p");
var format = str[i];
par.value = format;
div.appendChild(par);
}
}
The sixth function is an init function that handles the button click.
function init() {
var button = document.getElementById("analyse");
button.onclick = analyseButtonClick;
}
window.onload = init;
I have run this though a validator, and it shows me that there are no syntax errors, so it must be a logic error. However, all the functions seem to do what they are supposed to do, so I am not sure where I went wrong.
edit1: ok, have replaced the third function with four new functions. a function that returns the highest number in the array returned by getWordInfo, a function that constructs objects with name properties from 2 up to that number, a function that update the count properties of the objects, and a function that removes unused objects. here they are:
function maxNum() {
var array = getWordInfo();
var num = Math.max.apply(Math, array);
return num;
}
function objArrCon() { //object array constructor
var num = maxNum();
var array1 = [];
for (var i = 2; i === num; i++) {
var myObj = new objCon(i,0);
array1.push(myObj);
}
return array1;
}
function objArrParse() { //updates the object with word info
var array1 = getWordInfo();
var array2 = objArrCon();
var loopLength1 = array1.length;
var loopLength2 = array2.length;
for (var i = 0; i < loopLength1; i++) {
for (var m = 0; m < loopLength2; m++) {
if (array2[m].name === array1[i]) {
array2[m].count++;
}
}
}
return array2;
}
function objArrTrun() { //removes unused objects
var array1 = objArrParse();
var loopLength = array1.length;
for (var i = 0;i < loopLength; i++) {
if (array1[i].count === 0) {
array.splice(i, array1);
}
}
return array1;
}
still does not work, but im getting there!
I have written this in jQuery because 1) it's not my homework assignment and 2) it would be good practice (for you) to translate it back into normal JavaScript. You'll need to rewrite the event handler, along with the two getters/setters ($("text area").val() and $("tbody").append()).
Your main problem is that you have made your solution too complicated! If all you want to do is display the number, Y, of words with length, X, then you should do the following:
Grab the value of the text area and store in text
Remove all non-alphanumeric characters.
Split the text string wherever one or more spaces is present and store it in text
Loop through the array and map each array element, based on its length, to wordMap
Loop through wordMap and append it to wherever in the DOM you want the results to be
fiddle
JavaScript
$("#analyze").click(function () {
var text = $("textarea").val().replace(/[^\d\w ]+/g," ").split(/[ ]+/);
// this grabs the value of the text area, replaces all non-numerical
// and non-alphabetical characters with "", and then splits it into an array
// wherever one or more spaces is present.
var wordMap = {};
// makes an object that will be used as an associative array
text.forEach(function (d) {
// loops through the array
// if there is no key called d.length in wordMap
if (!wordMap[d.length])
wordMap[d.length] = 1; // set its count to one
else
wordMap[d.length]++; //otherwise, increment it
})
// loop through all the properties of wordMap
for (var x in wordMap) {
$("tbody").append("<tr><td>" + x + "</td><td>"
+ wordMap[x] + "</td></tr");
}
console.log(wordMap);
})
HTML
<textarea placeholder="type something..."></textarea>
<button id="analyze">Click to analyze</button>
<div id="results">
<table>
<thead>
<th>Length of Word</th>
<th>Number of Occurrences</th>
</thead>
<tbody>
</tbody>
</table>
</div>

Generate 7 unique random numbers in javascript

I have a project i'm working on.
I am to basically recreate lotto on the client side using javascript to generate 6 random numbers plus a bonus ball. as we all know, lotto numbers cannot be the same. this is where my question comes in.
Is it possible to remove a number that has been generated from being available in the next time round in the loop? This would make the function completely random. or do I need to still compare the number with the others in the array using indexOf?
for example, is the following possible?,
the first number that generates is 25,
the function then removes that number from being able to come up again.
so on...
Here is my js code,
function play(){
numbersArray = [];
for (i=0; i<=6;){
n = Math.floor(Math.random()*40)+1;
a = numbersArray.indexOf(n);
if ( a == "-1"){
numbersArray[i] = n;
i++;
var ballId = "ball"+i;
if( i != "7"){
document.getElementById(ballId).innerHTML = '<p>'+ n +'</p>';
} else {
document.getElementById("bonus").innerHTML = '<p>'+ n +'</p>';
}
} //end of if
}//end of for loop
}//end of play function
You need to create an object, in this case you could use an array, that holds all the possible numbers that can appear on the ball, we'll cal it n. Then you can use a while loop to keep picking numbers from that array, and splice/remove that specific number from the array on every iteration.
function play(n) {
var picks = [];
// Store possibilities in the numbersArr array
var numbersArr = [];
// n is the max number you can choose to appear on a ball
for ( var i = 0; i < n; i++ ) {
numbersArr.push(i);
}
while (picks.length < 7){
var randomIndex = Math.floor(Math.random() * numbersArr.length);
picks.push(numbersArr[randomIndex]);
numbersArr.splice(randomIndex, 1);
}
return picks;
}

Search Array in JavaScript

I need to sort through a data set which as you can see I've assigned to the records variable. From that data I need to see if the zip code exists. If the zip code does not exist then I need to move it into the array (There of course will be duplicates) and continue checking the rest of the records, if it does exist I need to do nothing.
// Declare Array
var numbersArray = [];
// Variables
var records;
var zipCode;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;
output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();
output.innerHTML = "The unique zip codes are: ";
while (records.readNextRecord()) {
zipCode = records.getSampleZipCode();
for (index = 0; index < numbersArray.length; index++) {
if (zipCode === numbersArray[index]) {
var uniqueZip = false;
break;
records++;
}
if (zipCode !== numbersArray[index]) {
numbersArray.push(zipCode);
}
}
output.innerHTML += numbersArray;
}
}
You can simplify your for loop like so:
matchedZip = false;
for(i in numbersArray) {
if (numbersArray[i] === zipCode) {
matchedZip = true;
}
}
if ( ! matchedZip) {
numbersArray.push(zipCode);
}
Try plugging that into your while loop. If you have the array push inside of the for loop you're going to end up pushing each zip code in every time there is not a match.
Well, you didn't exactly ask a question, but I'll answer anyway :) The answer is that you should not use a normal array for this, but rather a map or associative array. Fortunately a plain Javascript object can be used for this:
var numbers = {};
// Variables
var records;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;
output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();
output.innerHTML = "The unique zip codes are: ";
while (records.readNextRecord()) {
var zipCode = records.getSampleZipCode();
numbers[zipCode] = 1; // just picking an arbitrary value
}
for (var zipCode: numbers) {
output.innerHTML += zip + " ";
}
The reason is that this way you don't need to loop through the existing data for each new input.

Categories

Resources