Javascript Array - showing the index of the lowest number - javascript

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 :)

Related

Fibonacci Sequence - Starts at a specific # in javascript

//var myInputNumber=10;
function fibonacci(num) {
let fib = [1,1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}
console.log(fibonacci(10));
Complete javascript newbie here. I need help with a homework project. I have this work and displays up to the x (for easier display) Fibonacci numbers.
Here is the results from the above code: [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]
What I want to be able to do is specify the starting number/point (>=10, for example), and have it only display numbers from that point going forward.
So if my input number is 10, I want this result [ 13, 21, 34, 55, 89 ].
Use array filter and in the callback function return those element which are greater than the number passed as argument
function fibonacci(num) {
let fib = [1, 1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib.filter(function(item) {
return item > num
});
}
console.log(fibonacci(10));
just add another variable then
function fibonacci(num) {
let result = [];
let fib = [1,1];
for (let i = 2; i <= num; i++) {
let temp = fib[i-1] + fib[i-2];
fib.push(temp);
if(result>=num)
result.push(temp)
}
return result;
}
You may also want to define a limit to stop. The rest is pretty much similar to your existing code
function fibonacci(num, limit) {
let fib = [1,1];
for (let i = num; i <= limit; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}

How to fix my function trying to find min value in javascript

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);

How to find first element that's less than the x in an array in Javascript?

I have this question in which I wanted to loop through an array starting from large number to smaller number and compare the number in the array against the x provided.
My code was supposed to be like this:
function convertToRoman(num) {
var decimalNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
while (num > 0){ // to prevent the number from reaching zero
for (var k = 0; k < decimalNum.length; k++) { //to loop through the array
if(num > decimalNum[k]) {return k}; //this is the part in which I wanted to return the element that is next in the array that is less than the num
}
}
}
convertToRoman(36);
For example, if the num = 36, then the next number in the array that is less than 36 would be 10. So I wanted to return 10. How do I do that?
I tried to find solutions online but the only solutions I found was for Java or C++ which is completely different from JavaScript, correct? And I don't think that binary search should be used as well...
Return the value not the index you are on:
function convertToRoman(pNumber) {
var array = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
for (var i = 0; i < array.length; i++) {
if (pNumber > array[i]) {//if the current item is smaller than the parameter
return array[i]; //return the value at the index you are on
};
}
}
console.log(convertToRoman(36));//returns 10
When you get to a item that is smaller, then return that item
for that you should get the value not index
function convertToRoman(num) {
var decimalNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
// while (num > 0) { // to prevent the number from reaching zero
for (var k = 0; k < decimalNum.length; k++) { //to loop through the array
if (num > decimalNum[k]) {
return decimalNum[k]
}; //this is the part in which I wanted to return the element that is next in the array that is less than the num
}
// }
}
console.log(convertToRoman(36));
Here's a solution that will work in IE and regardless of how the values in the array are sorted
var lesser = decimalNum.filter(function(dec) {
return dec < num;
});
var result = Math.max.apply(null, lesser);
If you know that the decimalNum array is alwys sorted the way it is in your code, you can simply replace the Math.max part with lesser[0]

Every n times, skip n items and increase n by 1

This is probably an odd question since I have a solution (below), but was hoping someone could show me a more succinct or readable way to do this:
I created a loop that outputs the following array:
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91]
the gaps between numbers get progressively larger:
1-0 = 1
3-1 = 2
6-3 = 3
10-6 = 4
...
91-78 = 13
etc.
I did it by creating two variables, step keeps track of the gap size and count keeps track of the current 'position' in the gap. count counts down to zero, then increases step by one.
var output = [];
var step = 0;
var count = 0;
for (var i = 0; i < 100; i++) {
if (count == 0){
step += 1;
count = step;
output.push(i);
}
count -= 1;
}
You can try the following:
var output = [];
var total = 0;
for (var i=1; i < 100; i++) {
output.push(total);
total += i;
}
The gaps between numbers simply increase by one for each step, so a for loop should be able to track this change.
You should skip useless iterations. If you want a sequence of 100 numbers, use
var output = [];
var step = 0;
for (var i = 0; i < 100; i++) {
step += i;
output.push(step);
}
If you want the general term,
aₙ = ∑ⁿᵢ₌₀ i = n*(n+1)/2
So you can also do
var output = [];
for (var i = 0; i < 100; i++) {
output.push(i * (i+1) / 2);
}
You can save the total helper variable with this solution:
var output = [0]
for (var i = 1; i < 14; i++) {
output.push(output[i - 1] + i)
}
console.log(output) // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
This solution takes into account that the value to add the counter value to is already present at the last position in the array.
A recursive version is also possible:
output = (function f(x) {
return x.length == 14 ? x : f(x.concat([x[x.length - 1] + x.length]))
})([0])
console.log(output); // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
Here is no additional counter variable is needed. I use concat because it returns an array what I need for the recursive call, where push returns the new array length. The argument for concat is an array with one element with the new value to add.
Try online

Find next highest and next lowest number in a sequence

How to find the lowest and highest value couples in a sequence of number? I want to save the low/high values of a line graph.
Can you help me with a piece of pseudo code so people can implement the answer in their favorite prog language.
I will be using this to generate a line graph with D3.js. If anybody knows how to do this with D3 I would be more than happy to know about it.
Data Sample:
[20, 10, 11, 5, 15, 25, 10, 5, 15, 17, 26, 15, 7]
Desired Result:
array[0][high] = 20
array[0][low] = 5
array[1][high] = 25
array[1][low] = 5
array[2][high] = 26
array[2][low] = 7
This is what I have so far (in Javascript). Do you guys see anyway we can optimize this piece of code?
// data sample
var data_sample = Array(5, 15, 20, 15, 6, 11, 21, 14, 9, 4, 15, 20, 15, 1, 10, 20, 4);
// algo
var low = high = k = 0;
var log = [];
for (var i = 0; i < data_sample.length; i++) {
var current = data_sample[i];
var m = i+1;
var next = data_sample[m];
if (typeof next == 'undefined') {
break;
}
if (current < next) {
if (low === 0) {
low = current;
} else if (current < low) {
low = current;
}
} else if (current > next && low !== 0) {
if (high === 0) {
high = current;
} else if (current > high) {
high = current;
}
}
if (low > 0 && high > 0){
log[k] = [];
log[k]['low'] = low;
log[k]['high'] = high;
k++
low = high = 0;
}
};
Thank you in advance
Try this:
var arr = [20, 10, 11, 5, 15, 25, 10, 6, 15, 17, 26, 15, 7],
sorted = arr.sort(function(a,b){return a-b});
var array = [];
sorted.forEach(function(d,i){
var s = [];
s.push(sorted[i], sorted[(sorted.length-1) - i]);
array.push(s);
});
console.log(array);
Working fiddle here
The missing part of your code is how to store as array or object.
In your last if condition before you end the for loop you need to initialize log[k] as an object then add the property low and high like this
if (low > 0 && high > 0){
log[k] = {};
log[k].low = low;
log[k].high = high;
k++
low = high = 0;
}
Doing so will result is
array[0]{high: 20, low: 5}
array[1]{high: 25,low: 6}
If you want it to be an multidimensional array you do it like this:
Initialize log[k] as ab empty array.
if (low > 0 && high > 0){
log[k] = [];
log[k]['low'] = low;
log[k]['high'] = high;
k++
low = high = 0;
}
And the result
array[0]['high'] = 20
array[0]['low'] = 5
array[1]['high'] = 25
array[1]['low'] = 6

Categories

Resources