Javascript function parameters as an array [duplicate] - javascript

This question already has answers here:
How does the Math.max.apply() work?
(5 answers)
Closed 7 years ago.
Say for example I want the largest number out of an array of numbers.
var numbers = [54,34,76,33,87,12,76,92,44,93,23];
I want to be able to use Math.max() to find the largest number without using eval.
So, I want to be able to pass an array of parameters to a function. The array's length can change, so Math.max(numbers[0],numbers[1]...) won't work.
Is there any way I can do this?

You can use the .apply() method:
var max = Math.max.apply(Math, numbers);
The .apply() method is a property of Function.prototype and so is available on all function instances. Its first argument is used as the value of this in the function to be called, and the second argument should be an array that will be used as the list of parameter values.
In my example above I used Math as the value for this, because that's what this will be in a typical invocation of Math.max, but (on my installation of Firefox at least) Math.max.apply(null, numbers); works too.

Related

How to to make a varargs statement in javascript [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 1 year ago.
In javascript I am in situation where i need to make variable arguments based on a length of an array, below is an sample code
function getValesList(json){
return getValues(json[0])+getValues(json[1])+getValues(json[2]);
}
function getValues(json1){
let valueList = Object.values(json1);
let valueListPipe = valueList.join("|");
return valueListPipe+lineSeparator;
}
where json is an array of JSON objects and I need to make a pipe delimiter file based on the length of incoming array. How to make it dynamic where I can do like a varargs in JAVA
If you're just passing N arguments of the same type, you can use the rest feature of Javascript for function arguments.
function getValuesList(...json){
return json.map(j => getValues(j)).join("");
}
This allows you go pass any number of separate arguments as in getValuesList(o1, o2, o3, o4) and the json parameter within your function will automatically be an array of however many arguments were passed.

Reduce function only working once in JavaScript code [duplicate]

This question already has answers here:
How to call reduce on an array of objects to sum their properties?
(23 answers)
Closed 2 years ago.
I currently have to functions which use the Array.reduce method but only the first function works.
let profit = incomes.reduce((a,b) => a.getAmount() + b.getAmount());
Where a = a custom BudgetItem class with the method getAmount. I am wondering if this is a common JS thing or if I am doing something wrong.
Please note I have checked with the debugger and entering this line I have the same data in both methods.
According to mozilla the first parameter in Array.reduce() is the accumulator (the current sum) and the second is the current value from the array
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
So if you are trying to total the value from an array of BudgetItem you will want something like:
let profit = incomes.reduce((currentTotal, curremtIncome) => currentTotal + curremtIncome.getAmount());

what are some good scenarios in which to use reduce()? [duplicate]

This question already has answers here:
JavaScript - examples of reduce() function
(4 answers)
Closed 3 years ago.
What are some good scenarios in which to use reduce()? I've used map() and filter() quite a bit but I don't use reduce(), mainly b/c I'm not exactly sure what the niche/benefits of the reduce() function are.
Mainly, every scenario where you have to (ha!) reduce the initial array to one single element, while the other methods might also return an array whose length could be greater than 1

What does ‘...’ in JavaScript do? [duplicate]

This question already has answers here:
What "..." means in Javascript (ES6)? [duplicate]
(1 answer)
Spread Syntax vs Rest Parameter in ES2015 / ES6
(11 answers)
Closed 4 years ago.
I’m new to coding and slef teaching JavaScript.
My task I was set was to identify the largest value in an array.
My soloition works, but I needed the ‘...’ for it to work properly.
My question is, what does the ‘...’ in the last line actually mean/do?
function createAnArr(){
let myArr = prompt("Enter your numbers separated by commas:").split(",");
return myArr;
}
console.log(Math.max(...createAnArr()));
'...' it means it will be able to take any number of arguments of the respective scope
'...': The spread operator is used for array construction and destructuring, and to fill function arguments from an array on invocation. A case when the operator spreads the array (or iterable object) elements.
more details you can see here

How the sorting method of integer array works ? JS [duplicate]

This question already has answers here:
How does Javascript's sort() work?
(8 answers)
Closed 8 years ago.
var anArray = [ 5, 4, 8 , 1, 3] ;
anArray.sort(function (a,b){return a - b});
1) Can someone run me through how JavaScript will execute the sort method with function that is passed as a parameter ?
It will compare 5 with 4 then because it's positive, 4 will be before 5. Then it will compare 5 with every other number but 1 and 3 are also smaller than 5. So how java script know which position to put them before 5?
then it will compare 4 with every other number and 8 with every other number etc...
how java script do this? I want to do it with pen and paper.
2) why the function that is passed as an parameter is nameless ?
thank you.
Exactly how the comparator function will be called — that is, the sequence of values passed in — is not defined by the specification of the language. It completely depends on the particular JavaScript implementation and (probably) on the values in the array being sorted. Suffice to say that the sorting algorithm calls your function when it wants to compare two numbers, and that's that.The function is expected to return a value that's negative, zero, or positive, indicating that the ordering of the two numbers should be that the first one comes first, that either can come first, or that the second one should come first. A quick way to do that is to just subtract the second number from the first.
The function in your sample code is an anonymous function. It needs no name because it will be bound to a symbol in the receiving function as a result of the function call itself. You can give the function a name if you want to.

Categories