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);
Related
I am going through the grokking algorithms book and trying to wrap my head around recursion. One of the challenges in the book is to "Write a recursive function to count the number of items in a list.". I came up with the following code, which works:
function recursiveArrayCount(arr, count) {
if (arr.length == 0) {
return 0;
} else {
arr.pop();
return count + recursiveArrayCount(arr, count);
}
}
let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray, 1));
My question is, is there a better way to do this in javascript? In particular, I don't like having to seed the value of count with the initial '1' - but I can't think of another way to do it.
You don't need a second argument at all:
function recursiveArrayCount(arr) {
if (arr.length == 0) {
return 0;
}
return 1 + recursiveArrayCount(arr.slice(1));
}
Make a proper tail call by eliminating any reference to variables that would be needed after the recursive call returns.
function recursiveArrayCount(arr) {
return _recursiveCount(arr, 0);
function _recursiveCount(arr, count) {
return arr.length == 0 ? count : _recursiveCount(arr.slice(1), count + 1);
}
}
let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray));
This makes it more likely to be optimized by reusing stack space.
Also, I used a nested function for the recursion, which ensures that the count is properly initialized.
You could also get a little fancy with the inner function, like this:
function recursiveArrayCount(arr) {
return (function _recursiveCount(arr, count) {
return arr.length == 0 ? count : _recursiveCount(arr.slice(1), count + 1);
})(arr, 0);
}
let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray));
It's a recursively invoked IIFE.
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>
Complete JS newbie here!
I made an Array with a few numbers in it. I added a function that will show me the lowest number. My question can I show the index of the lowest number?(even If I would change the numbers)
Here is my code in case you need it:
function func()
{
var low= 0;
var numbersArr=[29, 26, 44, 80, 12, 15, 40];
for(var i = 0; i <= numbersArr.length;i++)
{
if(numbersArr[i]< numbersArr[i-1])
{
low = numbersArr[i];
}
}
console.log(low);
}
func();
You can also store value of i in one variable. See below code.
function func()
{
var numbersArr=[29, 26, 11, 44, 80, 12, 15, 40,10];
var low = numbersArr[0];
var indexOfLow;
for(var i = 0; i <= numbersArr.length;i++)
{
if(numbersArr[i]< low)
{
low = numbersArr[i];
indexOfLow = i;
}
}
console.log("Lowest number is : "+low);
console.log("Index of lowest number is : "+indexOfLow);
}
func();
My question can I show the index of the lowest number?
You can do
numbersArr.indexOf(low)
Edit
That said, your logic of finding the lowest number isn't correct as you are only comparing the consecutive values of the array, try the updated logic in demo below.
Demo
function func() {
var numbersArr = [29, 26, 11, 44, 80, 12, 15, 40];
var low = numbersArr[0];
for (var i = 1; i <= numbersArr.length; i++) {
if (numbersArr[i] < low ) {
low = numbersArr[i];
}
}
console.log(low);
console.log(numbersArr.indexOf(low));
}
func();
You function lack the problem of keeping the lowest value, because you compare only the actual element and the element before.
function getLowestValue(array) {
var low = 0,
i;
for (i = 0; i < array.length; i++) { // just loop i < array.length!
if (array[i] < array[i - 1]) {
// ^^^^^^^^^^^^ this is the problem, you need to check against low
low = array[i];
}
}
return low;
}
console.log(getLowestValue([29, 26, 11, 80, 12, 15, 40])); // 12 instead of 11
You could store the value of the lowest element and compare with this value.
function getLowestValue(array) {
var low = array[0], // take the first element at index 0
i;
for (i = 1; i < array.length; i++) { // start with index 1, because you need to
// check against the last known smallest value
if(array[i] < low) {
low = array[i];
}
}
return low;
}
console.log(getLowestValue([29, 26, 11, 80, 12, 15, 40])); // 11 the right value
For getting the lowest index, you could just store the index instead of th value and take it for comparison.
function getLowestIndex(array) {
var lowIndex = 0,
i;
for (i = 1; i < array.length; i++) {
if (array[i] < array[lowIndex]) {
lowIndex = i;
}
}
return lowIndex;
}
console.log(getLowestIndex([29, 26, 11, 80, 12, 15, 40])); // 2
No need to make a function to find minimum value. You can use simply Math.min.apply to find minimum value from array and then indexOf to find index of that value
var numbersArr = [29, 26, 44, 80, 12, 15, 40];
var minValue = Math.min.apply(null, numbersArr);
console.log("Minimum Value:"+ minValue, "Index is:" + numbersArr.indexOf(minValue));
Solution:You will declair a variable which will hold the index of low number and assign it in the if statement as shown below:
if(numbersArr[i]< numbersArr[i-1])
{
low = numbersArr[i];
IndexLow=i;
}
I found a super easy way to do that, in your way. Just little change in your code. Please take a look.
function func()
{
var numbersArr=[29, 31, 26, 44, 80, 123, 151, 40,15];
var low= numbersArr[0];
var index = 0;
for(var i = 1; i < numbersArr.length;i++)
{
if(low >= numbersArr[i])
{
low = numbersArr[i];
index = i;
}
}
console.log(index);
console.log(low);
}
func();
Hope you found your problem. Happy coding :)
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
I am working on a coding challenge to take a given array which consists of sub-arrays, search for the largest number in each sub-array, and finally return a new array consisting only of the largest numbers. My thought process was to create variables out of each subarray, write a for-loop comparing each value within the array, then push the largest value to a new array. After writing my first for-loop I tested my code and see that I am getting an unexpected result of the entire first subarray being pushed into my new array. I am looking for the mistake before I write the next three loops. Thank you. Edit: This is for beginner JavaScript coders and the suggestion indicates to use comparison operators in your solution.
function largestOfFour(arr) {
var one = arr[0];
var two = arr[1];
var three = arr[2];
var four = arr[3];
var newArr = [];
for (var i = 0; i < one.length; i++){
var oneLrg = 0;
if (one[i] > oneLrg){
oneLrg = one[i];
}
newArr.push(oneLrg);
}
return arr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]
Using >:
var newArr = [];
for(var i=0; i<arr.length; ++i) { // Iterate array
var maximum = -Infinity; // Initial maximum
for(var j=0; j<arr[i].length; ++j) // Iterate subarrays
if(arr[i][j] > maximum) // Compare
maximum = arr[i][j]; // Update maximum
newArr.push(maximum); // Store the real maximum
}
Using Math.max:
var newArr = [];
for(var i=0; i<arr.length; ++i) { // Iterate array
var maximum = -Infinity; // Initial maximum
for(var j=0; j<arr[i].length; ++j) // Iterate subarrays
maximum = Math.max(maximum, arr[i][j]); // Update maximum
newArr.push(maximum); // Store the real maximum
}
Adding apply:
var newArr = [];
for(var i=0; i<arr.length; ++i) // Iterate array
newArr.push( // Store ...
Math.max.apply(Math, arr[i]) // ... the maximum of the subarray
);
Adding ECMAScript 5 map,
var newArr = arr.map(function(subarray) {
return Math.max.apply(Math, subarray);
});
Adding ECMAScript 5 bind,
var newArr = arr.map(Function.apply.bind(Math.max, Math));
Or adding ECMAScript 6 arrow functions and spread operator,
var newArr = arr.map(subarray => Math.max(...subarray));
The problem here is that you're overwriting oneLrg at each loop iteration, and pushing it inside the same loop, so you're comparing each value to 0 and then, as one[i] is bigger, saving it.
Try this:
var oneLrg = 0;
for (var i = 0; i < one.length; i++){
if (one[i] > oneLrg){
oneLrg = one[i];
}
}
newArr.push(oneLrg);
No doubt that #Austin Hansen and I are leveraging the same learning environment for this challenge: Free Code Camp.
Having just worked through this challenge myself (FCC calls them "Bonfires"), I figured I'd provide solution that heavily dovetails from #Oriol 's excellent ">" solution.
I've included a specific note about the code blocks because to us newbies (at FCC or elsewhere), the absence of such can give us fits for hours : )
function largestOfFour(arr) {
var finalArray = [];
for(i = 0; i < arr.length; i++) { // iterates through each array
var max = -Infinity;
for(j = 0; j < arr[i].length; j++) { // iterates through each sub-array
if(arr[i][j] > max) { // comparing each successive element within the sub-array to what is currently stored as max
max = arr[i][j]; //if the ">" comparison is true then max gets updated
}
}
finalArray.push(max); // ensure this is OUTside of the j for loop. putting it INside the j for loop returns a very long (and wrong) array. try it.
}
console.log(finalArray);
return finalArray;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
https://jsbin.com/puweci/edit?js,console
FCC recognizes the follow solution which doesn't NOT leverage Array.push().
function largestOfFour(arr) {
var results = [];
for (var i = 0; i < arr.length; i++) {
var max = -Infinity;
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
results[i] = max;
}
return results;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");
This function will take two numbers and return their maximum:
var greatest = function(a,b){ return Math.max(a,b); };
This function will take an array of numbers and apply the greatest function to each number in turn (using the .reduce( callbackFunction, initialValue ) method of arrays) to get the maximum value in the array:
var findMaximum = function( arr ){ return arr.reduce( greatest, Number.NEGATIVE_INFINITY ); };
The findMaximum function can be simplified by just calling Math.max() with all the array values (eliminating the need for the greatest function); like this:
var findMaximum = function( arr ){ return Math.max.apply( Math, arr ); };
This function will take an array (of arrays) and call findMaximum on each element of it and return a new array containing those maximums (using the .map( callbackFunction ) method on an array):
var largestOfFour = function( arr ){ return arr.map( findMaximum ); };
This post hasn't had any new updates in about 3 months, but I figured I would post my solution to this problem as it looks a bit different than most of the other solutions posted thus far. Figured someone might find it helpful!
I am using quite a few built in method functions( .forEach, .sort, .push, .shift) a quick google search will explain each of these fairly well if you are unsure of how they work. https://developer.mozilla.org is a great resource for these.
function largestOfFour(arr) {
var newArr = []; //set up new empty array
arr.forEach(function(subArr){ //iterate through array with .each function
subArr.sort(function(a, b){ //use .sort to place largest number of each subarray into index[0]
return a < b;
});
newArr.push(subArr.shift()); //use .push method to .shift the index[0] number to newArr
});
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
You can have a look at this:
function largestOfFour(arr) {
var newArr=[];
largestnum=0;
for(i=0;i<arr.length;i++)
{
for(j=0;j<4;j++)
{
if(arr[i][j]>largestnum)
largestnum=arr[i][j];
}
newArr.push(largestnum);
largestnum=0;
}
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
#orion - Your answer to me was not working. If the push is inside the if statement was pushing numbers that were not suppose to be in the array. As a result the first would push [4,5] and wound't work. So I moved the push out of the for statement and reset the lgstNumber to 0 also after so it wouldn't use it for the next sub-array. This worked for me...
function largestOfFour(arr) {
// You can do this!
var newArr = [];
var lgstNumber = - Infinity;
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
if(lgstNumber < arr[i][j]){
lgstNumber = arr[i][j];
}
}
newArr.push(lgstNumber);
lgstNumber = 0;
}
return newArr;
}
function largestOfFour(arr) {
return arr.map(function(subArray) {
return subArray.reduce(function(firstArray, secondArray) {
return firstArray > secondArray ? firstArray : secondArray;
});
});
}
largestOfFour([[13, 27, 18, 26],[4, 5, 1, 3],[32, 35, 37, 39],[1000, 1001, 857, 1]
]);
its more efficient.
function largestOfFour(arr) {
for(var x=0;x<arr.length;x++)
{
for(var y=0;y<arr[x].length;y++)
{
arr[x]=arr[x].sort(function(a,b)
{
return b-a;
});
}
}
var array=[];
for(var a=0;a<arr.length;a++)
{
for(var b=0;b<arr[a].length;b++)
{
if(b==0)
{
array[a]=arr[a][b];
}
}
}
return array;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);