I am trying to find a number by using the input to search in the array.
Got any idea why this does not work?
Every time i run the code i only get the message:
"Number does not exist"
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var number = document.getElementById("find").value;
var svar = "";
function exists(){
for(i=0; i < arr.length; i++){
if(parseInt(arr[i]) == parseInt(number)){
svar++;
document.getElementById("existsArray").innerHTML = tall + "Number exists";
} else {
document.getElementById("existsArray").innerHTML = tall + "Number does not exist";
}
}
}
<p id="existsArray"></p>
<input placeholder="what number would you like to find?" id="find" type="number">
<button type="button" onclick="exists()">Finn tallet</button>
I replaced your for loop with indexOf
If you still want to use the loop you should break when you find the matching number
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var svar = 0;
function exists() {
var number = +document.getElementById("find").value;
if (arr.indexOf(number) !== -1) {
svar++;
document.getElementById("existsArray").innerHTML = "Number exists";
} else {
document.getElementById("existsArray").innerHTML = "Number does not exist";
}
}
<input type="number" id="find" />
<button onclick="exists();">Does it exist ?</button>
<p id="existsArray"></p>
If you want to get the number of occurrence you should use this :
var occurrences = arr.filter(function (num) {return num === number;}).length
So your problem is that you don't exit the loop when you find the matching number. As a result, unless the number you are looking for is the very last number in your array, it will keep looping and the else clause will execute.
function exist() {
var number = parseInt(document.getElementById("find").value,10);
for(i=0; i < arr.length; i++){
if (exists === arr[i]) {
// number exists
break; // <-- this is important another alternative would be to just
// return at this point if the function doesn't do anything else
}
else {
// this number doesn't match, so we'll keep searching
}
}
}
Of course, this is much easier if you just use the built in functions Array.prototype.find or Array.prototype.indexOf
You can also use a filter to keep only values in the array wich match with input :
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var input = "65";
var result = arr.filter(item => item === parseInt(input));
if (result.length === 0) console.log("number doesn't exist");
else console.log("number exists");
I've made some modifications to your code up front to help isolate your test case. If you look at this rework of your existing code, you'll see you get a message for each of your array elements, ending with "Number does not exist", which was your original problem. This is because that's the last message, overwriting your previous positive results.
var number = "42";
//var svar = "";
var svar = 0;//changing this from a string to a number. Can't ++ a string.
var myArray = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
/*
* #param {String} num - Passing the value that I'm looking for, rather than
* trying to pull it from elsewhere. This makes this much easier to test later.
* #param {Array} arr - Array of integers to search
*/
function exists(num, arr) {
for(i=0; i < arr.length; i++){
//if(parseInt(arr[i]) == parseInt(number)){
//No need to use parseInt here on the array. It's already a Number.
if(arr[i] == parseInt(number)){
svar++;/* I don't see any reason to be incrementing this. Perhaps it's elsewhere
in your implementation? */
//Using console.log() instead of elements not included in your code sample
console.log("Number exists");
} else {
//This keeps overwriting the above, except in a case where
//the last number would be a match!
console.error("Number does not exist");
}
}
}
exists(number, myArray);
If you want this to work as intended, you can either can eliminate your "Number does not exist" else branch, which will cause the positive message to remain, and you can leave your default text as "Number does not exist", or you simplify it, using what I'd recommend:
var number = "42",
number2 = "101",
myArray = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var existsSimple = function (num, arr) {
return myArray.filter(function (itemNum) {return itemNum === parseInt(num);}).length > 0;
};
console.log('Number exists: ' + existsSimple(number, myArray));//true
console.log('Number exists: ' + existsSimple(number2, myArray));//false
Related
The exercise says that I have to use a loop to check the array for numbers that contain the number '3'. The program must keep looping until all the numbers are listed. Currently it wont stop looping.
The exercise hints at making the numbers in array into a string. And also hints at the use of .indexOf() method.
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
var number_as_string = "" + some_array;
while (number_as_string.indexOf("3"))
{
process.stdout.write ("\n " + number_as_string);
}
process.exit();
The expected result is to list the numbers: 23, 36 and 300.
You could change your loop to a for loop, as below.
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
var result = [];
const numToLookFor = "3";
for(var i = 0; i > some_array.length; i++) {
var num = some_array =
if (num.toString().includes(numToLookFor)) {
result.push(some_array[i]);
}
}
You could also use an array.filter() method to achieve the same result.
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
const numToLookFor = "3";
var result = some_array.filter(num => num.toString().includes(numToLookFor));
Try this
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
var number_as_string = "" + some_array;
some_array.forEach(element => {
if (element.toString().includes("3")) {
console.log(element);
}
});
or
const ELEMENT_TRHEE = "3";
number_as_string.split(",").forEach(element => {
if (element.indexOf(ELEMENT_TRHEE) > -1) {
console.log(element);
}
});
This line of code won't convert your array od numbers into array of string. Instead it will convert the whole array into string
var number_as_string = "" + some_array;
This will output value as
"12,23,45,36,300,55,66,78"
and secondly, the while loop has not any termination condition that's why it is going into an infinite loop as indexOf will return some value always.
This code might help:
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
for (let num of some_array){
let num_in_string = num.toString()
if (num_in_string.indexOf("3") !== -1){
console.log(num_in_string)
}
}
process.exit();
Here I am looping through the array and getting each number in num variable as a number.
Then I am converting the number into a string using .toString() method.
The indexOf() method return either the index if present in the string or -1 is not found.
Thus the if block executes only if the returned value from indexOf is not -1 that means the "3" is present in the number and simply outputting it to console.
In case you are not familiar with toString() method, here is an alternative:
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
for (let num of some_array){
let num_in_string = num + ""
if (num_in_string.indexOf("3") !== -1){
console.log(num_in_string)
}
}
process.exit();
This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 3 years ago.
I am trying to format my array to a formatted string, how can I do that?
The instructions I was given are
Task 6 - find all odd numbers in a list.
Allow any number of Number arguments to be passed to the function.
If a value is passed to the function that is not a Number, ignore it
and continue processing the rest. If the list is empty (nothing passed
to the function, or all need to be ignored, return null).
Return a formatted string with all odd numbers in a list, for example:
"1, 3, 5"
<script>
var odd = [];
const oddNumbers = (...numbers) => {
var oddNum
var formatString;
var i;
if (numbers.length > 0) {
for (i = 0; i < numbers.length; i++) {
if (isNaN(numbers[i]) === false && (numbers[i] % 2 !== 0)) {
odd.push(numbers[i]);
console.log(odd);
}
}
} else {
return null;
}
return odd;
};
oddNumbers(1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13);
alert(odd);
</script>
Just join your array into string:
else{
return null;
}
return odd.join(', ');
const oddNumbers = (...numbers) => {
var odd = [];
var oddNum
var formatString;
var i;
if (Array.isArray(numbers)) {
for (i in numbers) {
if (isNaN(numbers[i]) === false && (numbers[i] % 2 !== 0)) {
odd.push(numbers[i]);
}
}
} else {
return [];
}
return odd;
};
var result = oddNumbers(1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13);
console.log(result.join(', '))
We have array of numbers, we need to find the total number of ways that we can remove one number in the array if removing that, will sort the array.
For example if we have [3,4,5,4] we should return 2 because if we remove 5 or the second 4 our array will be sorted.
But if we get something like [4,5,2,3,4] we should return 0 because removing any of them will not sort the array.
I believe that this is something related to Longest increasing subsequence
Correct me if I'm wrong, but this should work like this :
We should find the longest increasing subsequence and delete everything not in that subsequence.
With that in mind, I used some function like this to find the LIS :
function findSubsequence(arr){
var allSubsequence = [],
longestSubsequence = null,
longestSubsequenceLength = -1;
for(var i=0;i<arr.length;i++){ //i=1
var subsequenceForCurrent = [arr[i]],
current = arr[i],
lastElementAdded = -1;
for(var j=i;j<arr.length;j++){
var subsequent = arr[j];
if((subsequent > current) && (lastElementAdded<subsequent)){
subsequenceForCurrent.push(subsequent);
lastElementAdded = subsequent;
}
}
allSubsequence.push(subsequenceForCurrent);
}
for(var i in allSubsequence){
var subs = allSubsequence[i];
if(subs.length>longestSubsequenceLength){
longestSubsequenceLength = subs.length;
longestSubsequence = subs;
}
}
return longestSubsequence;
}
(function driver(){
var sample = [87,88,91, 10, 22, 9,92, 94, 33, 21, 50, 41, 60, 80];
console.log(findSubsequence(sample));
})();
But this give me the highest numbers, I'm not sure how should I remove one of them to keep the array sort and find all possible ways.
Any Idea?
That approach seems a bit complicated. I think it would be clearer and less resource-heavy to use a brute force approach: for every item in the array, try removing it, and then check to see if the array is sorted afterwards. But don't use sort to check if it's sorted (that has O(N log N) complexity), instead, just check to see that every item in the array is the same or greater than the previous one (O(N)):
const checkSorted = arr => arr.every((num, i, arr) => i === 0 || num >= arr[i - 1]);
const checkRemovalCount = arr => arr.reduce((countSoFar, _, i, arr) => {
const removedArr = [...arr.slice(0, i), ...arr.slice(i + 1)];
return countSoFar + checkSorted(removedArr);
}, 0);
console.log(checkRemovalCount([3,4,5,4]));
console.log(checkRemovalCount([4,5,2,3,4]));
console.log(checkRemovalCount([87,88,91, 10, 22, 9,92, 94, 33, 21, 50, 41, 60, 80]));
You can remove highest number using Math Library.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var sample = [87,88,91, 10, 22, 9,92, 94, 33, 21, 50, 41, 60, 80];
sample.sort(function(a, b){return a - b});
list = remove_highest(sample)
console.log(list) // [9, 10, 21, 22, 33, 41, 50, 60, 80, 87, 88, 91, 92]
function remove_highest(list) {
return list.filter(function(n) { return n != Math.max.apply( Math, list ) })
}
</script>
</body>
</html>
sorry for the noob question probably, but I can't get my function to work. For me it looks very similar to the resolutions found on the web, but somehow it doesn't work and I can't tell where is the problem. Would be grateful for any help
function findvalue() {
var i = 0;
var array = [];
var min = array[0];
for (i = 0; i < array.length; i++) {
if (min > array[i]) {
min = array[i];
}
}
return min;
}
console.log(findvalue(11, 12, 13, 21, 22, 23, 97, 98, 99))
;
You could use arguments, an array like object of the function.
function findvalue() {
var i = 0,
min = arguments[0];
for (i = 1; i < arguments.length; i++) {
if (min > arguments[i]) {
min = arguments[i];
}
}
return min;
}
console.log(findvalue(11, 12, 13, 21, 22, 23, 97, 98, 99));
A shorter approach could be the use of rest parameters ... and spread syntax ... for the values for Math.min.
function findvalue(...args) {
return Math.min(...args)
}
console.log(findvalue(11, 12, 13, 21, 22, 23, 97, 98, 99));
Your function definition is incorrect, as well as how you are calling your function.
You are looking to iterate over an array, but you are calling your function with a bunch of numbers as the arguments. You instead need 1 parameter (argument) to call your function, which should be an array .
You have to instead call it this way:
findvalue([11, 12, 13, 21, 22, 23, 97, 98, 99])
Your function definition needs to be:
function findvalue(array) {
var i = 0;
var min = array[0];
for (i = 1; i < array.length; i++) {
if (min > array[i]) {
min = array[i];
}
}
return min;
}
As noted in the comments, you could modify your function definition to retain your initial way of calling the function. This is done by using rest parameters
The MDN docs describe rest parameters as:
The rest parameter syntax allows us to represent an indefinite number
of arguments as an array.
Call the function as you did: findvalue(11, 12, 13, 21, 22, 23, 97, 98, 99)
Your function definition would be:
function findvalue(...array) {
var i = 0;
var min = array[0];
for (i = 1; i < array.length; i++) {
if (min > array[i]) {
min = array[i];
}
}
return min;
}
You can use Math.min
function findMin() {
// arguments is an Array-like object corresponding to the arguments passed to a function.
return Math.min.apply(Math, arguments)
}
console.log(findMin(2,4,1,0,9,-2));
The missing thing in your function is the array must be a parameter of your function.
As you wrote it, the function is always trying to find the minimum in an empty array.
It is currently completely ignoring the example values you passed when you called your function.
So, instead of writing var array = [] in the body of you function, you have several possibilities :
1st possibility : take the array as parameter : declare your function as function(array) and change your call to actually pass an array of values : findValues([11, 12, 13, 21 ...]), and remove the var array = [] inside the body of your function.
2nd possiblity (my favorite): just replace var array = [] by var array = [...arguments]
Documention on the arguments object here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
(and also, please note that let is now best practice than var)
See Nina 's answer for full snippets examples with arguments
try like this
function findvalue() {
var order = Array.from(arguments).sort(function(a,b){ return a - b; });
var min = order[0];
//var max = order[order.length-1];
return min;
}
// MIN value
console.log(findvalue(23, 97, 98, 99, 11, 12, 13, 21, 22));
I am sure the Arrow function will simplify your work.
//Variable diclaration
var numbers = [11, 12, 13, 21, 22, 23, 97, 98, 99];
//Arrow Function to find Min Number
var minfinder = numbers.reduce((a, b) => Math.min(a, b));
//Consloe Output
console.log("Min Number is: " + minfinder);
nodeArray = [ 3, 3, 7, 6, 6, 7, 15, 10, 10, 14, 13, 13, 14, 15, 23, 18, 18, 22, 21, 21, 22, 23, 0 ];
nodes = [];
links = [];
function left(i) {
return 2*i + 1;
}
function right(i) {
return 2*i + 2;
}
function parent(i) {
console.log("Parent =" + (i-1)/2);
return (i-1)/2;
}
var index = 0;
do{
if (index === 0) {
var node = {
'value': nodeArray[index],
'child1_index': left(index),
'child1_value': nodeArray[left(index)],
'child2_index': right(index),
'child2_value': nodeArray[right(index)],
'parent_index' : 'null',
'parent_value' : 'null'
};
} else {
var node = {
'value': nodeArray[index],
'child1_index': left(index),
'child1_value': nodeArray[left(index)],
'child2_index': right(index),
'child2_value': nodeArray[right(index)],
'parent_index' :parent(index),
'parent_value' : nodeArray[parent(index)],
'index' : index
};
}
nodes.push(node);
index++;
} while (index != nodeArray.length)
console.log(nodes);
I have written the above code for future turning it into a binary tree with d3.js library, unfortunately all my parent node values (which are apparently given by any nodes (index -1 )/ 2. give numbers like 5.5 etc being half the index or something. which obviously wont work. Some nodes give full integers then some do not.
example console output for one of my node objects. which looks right
Node1:
parent_index:0
parent_value:3
example of other node objects. which dont look right are
Node2:
parent_index:0.5
parent_value:undefined
Here is a jsfiddle if anyone's interested
http://jsfiddle.net/mryfw095/5/
I think you just want your parent function to round down.
function parent(i) {
console.log("Parent =" + Math.floor((i-1)/2));
return Math.floor((i-1)/2);
}