I want to get array using given min , max range - javascript

I want to get an output array beginning with min value and ending with max value => [5,6,7,8,9,10].
But I get only min value in new array => [5]. Why does this happen?
function arrayFromRange(min , max){
const newArray = [];
for( let x = min ; x <= max; x++ ){
newArray.push(x);
return newArray;
}
}
const newarray1 = arrayFromRange(5,10);
console.log(newarray1);

You return your newArray inside the for loop, having only added the first item, in this case 5.
Solution is to move the return out of the foor loop, i.e.
function arrayFromRange(min , max){
const newArray = [];
for( let x = min ; x <= max; x++ ){
newArray.push(x);
} // <--swap these
return newArray; // <-- two lines
}

Related

vue3 find min value from an array

I'm trying to get the minimum value from an array in Vue3 but I keep getting an infinity value. Can I please get help?
Below is adding value to the 'ranks' array.
const ranks = ref([])
for (let i = 0; i < uni.value.length; i++) {
ranks.value.push(uni.value[i].rank)
}
And here is the finding min code:
const min = Math.min(...ranks.value)
console.log(min) // it returns Infinity
this is how my ranks array looks in the console:
const minValue = (nums) => {
let min = Infinity;
for(let i=0; i< nums.length;i++){
if(min > nums[i]){
min = nums[i];
}
}
return min;
};
Use the below code to find the minimum value.
a = [5,4,1,2,3]
let minVal = Infinity
a.forEach(val => minVal = minVal > val ? val : minVal)
console.log('Minimum value is ' + minVal)

Birthday Cake Candles HackerRank withoug Math.max Javascript

You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest.
Example
Candles = [4,4,1,3]
The maximum height of candles is 4 units high. There are 2 of them, so return 2.
So basically the way I'm doing so is by moving from each place of the array comparing each other with two for cycles, the second cycle will count the repeated numbers, some people use Math.max imported function but I didn't know it before started looking for the answer, and I think this way should work, but can't get to the answer, any ideas?
function birthdayCakeCandles(candles) {
let height=1;
let b=0;
for (let i=0; i<candles.length; i++)
{
for (b=0; b<candles.length; b++)
{
if(b!=i && candles[b]===candles[i])
{height++;}
b++;
}
}
return height;
This should be straightforward, iterate through the array find max if max exists again increase count, if some other element greater than max set it to max and reset count to 1
function findTallestCandleCount(candles){
let max = 0, count = 0
for (let candle of candles) {
if (candle > max) {
max = candle
count = 1
} else if (candle === max){
count++
}
}
return count;
}
I solved it this way
function birthdayCakeCandles(candles) {
let height=0;
let max=Math.max(...candles);
for (let i=0; i<candles.length; i++)
{
if (candles[i]==max)
{height++;}
}
return height;
}
well I solved that challenge with this
function birthdayCakeCandles(candles) {
const maxVal = Math.max(...candles)
//use an array to save all the biggest/max number
const newArr = []
for(let val of candles){
if(val === maxVal) {
newArr.push(val)
}
}
return newArr.length
}
But If you don't want to use Math.max() we have to find biggest value first. we can use for of loop to find max/biggest value like this:
function birthdayCakeCandles(candles) {
let maxVal = 0
//use loop to find the biggest number
for(let val of candles) {
if(val > maxVal) {
maxVal = val
}
if(val < maxVal) {
maxVal = maxVal
}
if(val === maxVal) {
maxVal = maxVal
}
}
//use an array to save all the biggest/max number
const newArr = []
for(let val of candles){
if(val === maxVal) {
newArr.push(val)
}
}
return newArr.length
}
You can try this below.
The logic that i used is that first store the values in newArr[] with candles[0] and Highest numbers from candles[] array. It is because the logic used in first for loop that compares max_val = candles[0] with candles[i]. And so when storing max_val to newArr[], it taking candles[0] and its comparing values (equal to or greatern than candles[0]) along with largest numbers in candles[] array.
Now the second for() loop filtering values based on max_val == newArr[j]. The max_val in first for() loop already loaded with largest value, so that after comparison only largest numbers are filtered and stored into resultArr[]. Then return the function with length property.
var max_val = candles[0];
var newArr = [];
var resultArr = [];
var resultMax;
for(var i = 0; i < candles.length; i++)
{
if(max_val <= candles[i])
{
max_val = candles[i];
newArr.push(candles[i]);
}
}
for(var j = 0; j < newArr.length; j++)
{
if(max_val == newArr[j])
{
resultArr.push(newArr[j]);
}
}
var num = resultArr.length;
return num;

Passing array as argument to a js function

I wanted to create a basic function summing up values from an array. I'm aware of the array reduce method but i wanted initially to use a loop "for" instead as below...however it returns NaN...why ?
var numbers=[1,2];
var total;
function sum(array){
total=0;
for(var x=0;x<=array.length;x++){
total += array[x];
}
return total;
}
Do sum(numbers), also in your loop the break condition should be x<array.length; also you do not need to make total a global variable to continue adding values of array to it.
var numbers = [1, 2];
function sum(array) {
var total = 0;
for (var x = 0; x < array.length; x++) {
total += array[x];
}
return total;
}
var total = sum(numbers);
alert(total);
Though the shorter way will be to use .reduce on the array
var array = [1,2]
var sum = array.reduce(function(prev, curr) { return prev + curr; }, 0);
alert(sum);
Here You can also provide an Arrow Function instead of a full function.
var array = [1, 2]
var sum = array.reduce((prev, curr) => prev + curr);
alert(sum);
You get NAN because, as the loop's condition isx<=array.length, the last iteration adds array[length] to the sum, while the last item of the array is array[length - 1]
You could also use reduce to sum up all elements:
sum = array.reduce(function(a, b) { return a + b; }, 0);
If you want to stay on your initial approach, then you don't have to return global variable from within function. You can change global variables inside function directly;
var numbers=[1,2],
total;
function sum(array){
total=0;
for(var x = 0, len = array.length; x < len; x++){
total += array[x];
}
}
In other cases, of course, using of local variables is preferable when you intend to form independent results

Find value of 100 latest values in array

I've got an array that is constantly updating with analogue readings from an Arduino pin.
I'd like to create a function that takes the latest 100 values in the array, and returns an average of them (the array has a max length of 100,000 at which it starts 'shifting' and 'pushing' to make space for new values).
I created this function, but it returns 'NaN' every time:
function returnAverage(){
var averageArray = [];
var sum = 0;
var sampleEnd = values.length
for (var x = sampleEnd - 100; x < sampleEnd; x++) {
averageArray[x] = values[x]
}
for(var i = 0; i < averageArray.length; i++){
sum += parseInt(averageArray[i]);
}
var avg = sum/averageArray.length;
console.log(avg)
}
Any ideas?
If values is a array of numbers, last maximum 100 items average:
function returnAverage(values) {
var arr = values.slice(-100);
return arr.reduce(function(a, b){ return a + b; }, 0) / (arr.length || 1);
}
Issue number one is that the final value of sum and averageArray.lnegth is 0.
It seems this would happen because the "value" array is empty.
See example below:
var values = [0,1,2,3,4,5,6];
var averageArray = [];
var sum = 0;
var sampleEnd = values.length
for (var x = sampleEnd - 7; x < sampleEnd; x++) {
averageArray[x] = values[x]
}
for(var i = 0; i < averageArray.length; i++){
sum += parseInt(averageArray[i]);
}
var avg = sum/averageArray.length;
console.log(avg)
Edit: NaN is a result of division by zero. So you might want to check for that before calculating:
if(sum == 0 || averageArray.length == 0)
{
return 0;
}

Smallest number in array and its position

What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.
Just loop through the array and look for the lowest number:
var index = 0;
var value = temp[0];
for (var i = 1; i < temp.length; i++) {
if (temp[i] < value) {
value = temp[i];
index = i;
}
}
Now value contains the lowest value, and index contains the lowest index where there is such a value in the array.
One-liner:
alist=[5,6,3,8,2]
idx=alist.indexOf(Math.min.apply(null,alist))
You want to use indexOf
http://www.w3schools.com/jsref/jsref_indexof_array.asp
Using the code that you had before, from the other question:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
Array.min = function( array ){
return Math.min.apply( Math, array );
};
var value = temp.min;
var key = temp.indexOf(value);
Find the smallest value using Math.min and the spread operator:
var minimumValue = Math.min(...temp);
Then find the index using indexOf:
var minimumValueIndex = temp.indexOf(minimumValue);
I personally prefer the spread operator over apply.
See this answer of "find max" version of this question. It is simple and good. You can use the index to get the element afterward.
You could use reduce, and compare against Infinity.
let minIndex = -1;
arr.reduce((acc, curr, index) => {
if (curr < acc) {
minIndex = index;
return curr;
} else {
return acc;
}
}, Infinity);
Here is a solution using simple recursion. The output is an object containing the index position of the min number and the min number itself
const findMinIndex = (arr, min, minIndex, i) => {
if (arr.length === i) return {minIndex, min};
if (arr[i] < min) {
min = arr[i]
minIndex = i;
}
return findMinIndex(arr, min, minIndex, ++i)
}
const arr = [5, 5, 22, 11, 6, 7, 9, 22];
const minIndex = findMinIndex(arr, arr[0], 0, 0)
console.log(minIndex);

Categories

Resources