checking for a value in an array - javascript

My function to check if a value is in an array returns false every time, even if it should be true.
When I change var value to be, let's say 20, and I run the page until 20 appears in the array, it works and returns true. However when the value is the prompt, and I type in a number that appears in the array, I always get false.
function checkIfInArray(n, anArray) {
return anArray.indexOf(n) > -1;
}
var array = new Array();
for (var i = 0; i < 10; i++) {
array[i] = Math.floor(Math.random() * 101);
}
alert("The array is " + array);
var value = prompt("Enter a value to check if it is in the array");
var result = checkIfInArray(value, array);
alert(result);

Your array contains numbers, prompt() returns a string. You need to convert the string into a number, which you can do with parseInt().
function checkIfInArray(n,anArray) {
return anArray.indexOf(n) > -1;
}
var array=new Array();
for (var i = 0; i < 10; i++)
{
array[i] = Math.floor(Math.random()*101);
}
alert("The array is " + array);
var value=parseInt(prompt("Enter a value to check if it is in the array"), 10);
var result=checkIfInArray(value,array);
alert(result);

Try like this
function checkIfInArray(n,anArray) {
return anArray.indexOf(parseInt(n)) > -1; // parse int . here was the problem
}
var array=new Array();
for (var i = 0; i < 10; i++)
{
array[i] = Math.floor(Math.random()*101);
}
alert("The array is " + array);
var value=prompt("Enter a value to check if it is in the array");
var result=checkIfInArray(value,array);
alert(result);

You have a type issue, the prompt result is a string not an int and the indexOf method use a strict mode to compare the elements, so you should cast the value to an int before call indexOf:
return anArray.indexOf(parseInt(n)) > -1;
*Note that the Array.indexOf is not supported in IE8

You're probably getting that error because the prompt is sending a string and not a number. Try using parseInt() to convert the string to an integer to test the value.
You could do either
var value = parseInt(prompt("Enter a value to check if it is in the array"));
or
var result = checkIfInArray(parseInt(value), array);

Related

Comparing values between two arrays

I'm trying to set up a function that checks if a word or a text is a palindrome. To do that, it splits the text so that every letter is an element of a new array, it takes rid of the white spaces and it makes the reverse array.
Then it checks if every element of the two arrays, at the same positions, are equal. If not it returns false, if yes it returns true.
Here the function:
function palindrome(str) {
var low = str.toLowerCase();
var newArray = low.split("");
var noSpace = newArray.filter(function(val) {
return val !== " ";
});
var reverse = noSpace.reverse();
function check (a, b) {
console.log(`checking '${a}' against '${b}'`);
var partial;
var result = 1;
for (var i = 0; i < a.length; i++) {
console.log(`comparing '${a[i]}' and '${b[i]}'`);
if (a[i] !== b[i]) {
result = 0;
} else {
partial = 1;
result *= partial;
}
}
return result;
}
var result = check(noSpace, reverse);
if (result == 1) {
return true;
} else {
return false;
}
}
palindrome("r y e");
I don't know what's wrong but it seems that the function keeps on returning a true value no matter what word or text I pass to the function. What is wrong with that?
Your issue seems to be because reverse() changes the actual array as well. So doing
var reverse = noSpace.reverse();
Will reverse noSpace and assign a reference to it on the variable reverse. That is, both arrays will be the same (reversed) array.
To bypass that, I've used .slice() to create a copy of the original array, and then called .reverse() on that new array, ridding you of any conflicts.
Here's a working snippet of what it looks like:
function palindrome(str) {
var str_array = str.toLowerCase().split("");
var no_space = str_array.filter(function(val) {
return val !== " ";
});
// By applying '.slice()', we create a new array
// reference which can then be reversed and assigned
// to the 'reverse' variable
var reverse = no_space.slice().reverse();
function check(a, b) {
var partial;
var result = 1;
for(var i=0; i < a.length; i++) {
if(a[i] !== b[i]) {
// We don't need to keep
// comparing the two, it
// already failed
return 0;
} else {
// I've kept this part even though
// I don't really know what it is
// intended for
partial = 1;
result *= partial;
}
}
return result;
}
return check(no_space, reverse) === 1;
}
console.log(palindrome("a b a"));
console.log(palindrome("r y e"));
The way you have coded for palindrome is way too complicated.
But there is one problem with your code: when you do a reverse() it changes the original array as well.
So you will need to make sure that you copy it via slice().
Also you can directly send a boolean result rather than doing a 1 and 0.
At result *= partial;, 1 * 1 will always equal 1
I didn't correct your code, but here is a optimized solution for you.
function palindrom(string) {
var arr = string.split("");
var lengthToCheck = Math.floor(arr.length / 2);
for (var i = 0; i < lengthToCheck; i++) {
if (arr[i] != arr[arr.length - (1 + i)]) {
return false;
}
}
return true;
}
First I split the array after every charater of the passed String. After that I get the half of the length of the array as it's enough to check just one half.
With the for-loop I compare the first half with the second half. As soon as I found two characters that do not match I return false. In case the whole first half matches the second half of the array, the for-loop will be completed and after that true will be returned.
What's actually happening is .reverse() reverses an array in place, it then stores a reference to that array which is not what you're calling in your check() method.
Simple fix would be to change your if statement:
if (a[i] !== b.reverse()[i])

Convert number into amount of space

I have a number and want it to generate to a string with corresponding space
For Example:
var NumberOfSpace = 3;
// This will result in a string with 3 empty space
// the result will be " "
var space = convertToSpace(NumberOfSpace);
You can simply use the String.prototype.repeat method:
" ".repeat(3);
A polyfill for older browsers.
A concise option:
function convertToSpace(n) {
return new Array(n + 1).join(' ')
}
Here is a convertToSpace function
var convertToSpace = function (spaces) {
var string = "";
for (var i = 0; i < spaces; i++) {
string += " ";
}
return string;
}
Using Array#fill and Array#reduce
The fill() method fills all the elements of an array from a start index to an end index with a static value.
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
var NumberOfSpace = 3;
function convertToSpace(param) {
return new Array(param).fill(' ').reduce(function(a, b) {
return a + b;
});
}
var space = convertToSpace(NumberOfSpace);
console.log(space);

how can I do an addition of all price elements from a json array in javascript

I have the following JSON array:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
How can I calculate all the "price" values together? The result should be 8.
I have so far the following but problems accessing the price items:
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum = sum + fruits[i][price];
}
return sum;
}
console.log(count(fruits)
Thank you!
You need to access them like:
fruits[i].price
and then convert them to numbers before adding them:
parseInt(fruits[i].price, 10);
Final code:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
var total = 0;
for(var i=0; i<fruits.length; i++){
total += parseInt(fruits[i].price, 10);
}
alert(total); //8
See the DEMO here
Two things:
The line
sum = sum + fruits[i][price];
should be
sum = sum + fruits[i].price;
or even
sum += fruits[i].price;
Your code was trying to use a variable called price, not the price property of the fruit entry.
Your prices are strings, so we want to make sure they're converted to numbers when summing them up. You have lots of options there: Apply a unary + to them, pass them into Number(), or use parseInt(..., 10). Below I'll go with a unary +, but there are pluses (no pun!) and minuses to each.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum += +fruits[i].price; // <=== change is here
}
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
With ES5's array additions (which can be shimmed on older browsers), you can do this with either forEach or reduce:
forEach:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
fruits.forEach(function(fruit) {
sum += +fruit.price;
});
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
reduce:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
sum = fruits.reduce(function(prev, fruit) {
return prev + +fruit.price;
}, 0);
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Your code has 2 errors:
To access the price property
fruits[i][price]
should be
fruits[i]['price'] or fruits[i].price
The price property is of type string. So the '+' operator will concatenate the price strings. To add them together you need to change their type to number by doing
parseInt(fruits[i]['price'], 10) or +fruits[i]['price']
If the price property doesn't contain a valid number the result will be NaN (not a number). You could avoid that by using the or operator.
+fruits[i]['price'] || 0
Using the ES5 Array extensions supported by all modern browsers you could write
fruits.reduce(function(m,v) { return m + (+v.price);}, 0);
With ES6 in future browsers this could be reduced to
fruits.reduce((m,v) => m + (+v.price), 0);
You have some errors in your code.
The first one is here: sum = sum + fruits[i][price];
you are trying to use a variable called price, not the property price of the object. You can access to the property using fruits[i]["price"] or fruits[i].price.
To obtain a number, when you are doing the sum, you need to convert the strings in numbers, to do that you can use parseInt(fruits[i]["price"]);. Last error in the last line you forgot the parenthesis and semicolon.
JSFiddle
your function is OK, just add parseInt for it to convert to type int, and has a incorrect syntax in fruits[i][price].
You've two option:
fruits[i]["price"]
OR
fruits[i].price
In my opinion, I would add a small logic code to check if it's a number or not. and return 0 if input data is undefined or null.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(data) {
var sum = 0;
if(data === void 0 ) return 0; // no array input
data.forEach(function(fruit) {
console.log(fruit);
sum += parseInt(fruit.price || 0 ); // if price is undefined, null or NaN, return 0
})
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
You should try this simple code snippet.
You don't need jQuery to do this operation. Simple JS would do.
var sum = 0;
for(var item in fruits){
sum += ~~(fruits[item].price)
}
console.log(sum)
Cheers!

Getting range from a list using regular expressions

I have a list of numbers such as
var list = ["123","12345678","123","234,2345","2.34567","123.12345","-123","-0.1234","-324215.45"];
This list can have negative, positive numbers with optional decimal values, also negative or positive.
I need to use regular expressions to do 3 things:
getAllNumbersBeforeValue(value);
getAllNumbersAfterValue(value);
getRangeBetweenValues(valueFrom, valueTo);
Value passed in is not known, could be any number.
Update 1:
I've got this, which isn't perfect but works on some numbers:
var a = function(rand) {
var val = "";
var numArr = rand.split("");
for(var i = 0; i < numArr.length; i++) {
val = val + (Number(numArr[i])+1);
}
return "^[^" + val.split("").join("-9][^") + "-9]$"
}; // outputs "^[^2-9][^3-9][^4-9][^5-9][^6-9]$" with rand "12345"
Im trying to get a regular expression programmatically generated from a given value
For example "123456" is a random number (rand), I would like to be able to filter an array of numbers for values that are higher then rand (or lower then rand) using a regex value.
Thanks
You could use underscore.js (http://underscorejs.org) to filter your results. For example...
var list = ["123","12345678","123","234,2345","2.34567","123.12345","-123","-0.1234","-324215.45"];
function getAllNumbersBeforeValue(list, value) {
return _.filter(list, function(num) {
return num < value;
});
}
Here's an example without using a framework...
function getAllNumbersBeforeValue(list, value) {
var output = [];
for(var i = 0; i < list.length; i++) {
if(list[i] < value) {
output.push(list[i]);
}
}
return output;
}
getAllNumbersBeforeValue(list, 123);

Unique random number generation using javascript

I use the following code for generating the random number from 0 to 15. I use a function random() for generating the unique number i call the function like this
cat=random();
I save the random number with in the array r[]. and check the newly generating number is in the array or not. If the duplicate occurs i call the random() function once again. I use alert for just check it correctly working or not
function random(){
var ran,max=0,min=0;
max=r.length;
alert(max);
if (max>15)
alert("no more space");
ran=Math.floor(Math.random() * 15) + 0;
for (i=0;i<max;i++)
if (ran==r[i])
min++;
if (min>0){
alert("calling");
random(); //return in here
}else{
i=parseInt(max);
r[i]=ran;
return(ran);
alert(ran);
}
}
But the variable return within the function when the duplication occurs can anybody help with this.
I'd create an array and shuffle it using Fisher-Yates.
function shuffle(arr) {
var shuffled = arr.slice(0), i = arr.length, temp, index;
while (i--) {
index = Math.floor(i * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled;
}
// Create the array
var i = 16, arr = [];
while (i--) arr[i] = i;
// Shuffle it
arr = shuffle(arr);
// Array is now the numbers 0-15 in a random order
console.log(arr);
Bored, quick hack job, but I believe it'll work:
// Minimum random number
var min = 0;
// Maximum random number
var max = 15;
// Returns a random number between min and max
function random() {
var random_number = Math.random();
return Math.floor((random_number * max) + min);
}
// Returns false if number is in the array
function random_is_unique(random_num_, array_) {
// Could use indexOf, but just looping here for simplicity.
// And not so sure IE has this capability.
for(i = 0; i < array_.length; i++) {
if(array_[i] == random_num_) {
return false;
}
}
return true;
}
// Returns a guaranteed unique, or -1 if no more unique values
// are availble to return
function guaranteed_unique(array_) {
random_number = random();
// Just an iterator, so we have a terminating condition
tries = 0;
while(!random_is_unique(random_number, array_)) {
// This is dumb. There's likely a better way to do this, but it's
// quick and dirty. It also does not guarantee you've tested all
// integers.
if(tries > max) {
return -1;
}
random_number = random();
tries++;
}
return random_number;
}
my_array = new Array();
my_array[0] = 1;
my_array[1] = 15;
my_array[2] = 6;
my_array[3] = 9;
my_array[4] = 13;
my_random_number = guaranteed_unique(my_array);
alert("Random number is " + my_random_number);
i modified a solution that was useful fr me
it gets rid of empty entries between numbers and fills them with unique number between 1-9
var arr = [,2,,4,,6,7,,]; //**example**<br/>
while(arr.length < 9){<br/>
var randomnumber=Math.floor(Math.random()*9+1);<br/>
var found=false;<br/>
for(var i=0;i<arr.length;i++){<br/>
if(arr[i]==randomnumber){found=true;break;}<br/>
}<br/>
if(!found)<br/>
for(k=0;k<9;k++)<br/>
{if(!arr[k]) //**if it's empty !!MODIFICATION**<br/>
{arr[k]=randomnumber; break;}}<br/>
}<br/>
alert(arr); //**outputs on the screen**<br/>

Categories

Resources