There are two concepts at stake here, the first one is "rest params"
function minimoAbsoluto(...arreglos) {
the use of " ...arreglos
" means that all parameters that do not yet have a name / assigned variable are put together in an array " arreglos
", if you want to name the first parameter and group the rest:
function minimoAbsoluto( a, ...arreglos) {
I would take the first parameter in " a
" and the rest in an array " arreglos
"
Second concept "spread syntax"
return Math.min(...arreglos);
In this case the use of " ...arreglos
" scatters the elements of "fixes" separated by commas. Because in the first " ...arreglos
" (rest params) you put several arrays in one, when you scatter them, they are still arrays separated by commas.
var arreglosTest1 = [21, 9, 34],
arreglosTest2 = [9, 8, 13];
function minimoAbsoluto(...arreglos) {
console.log("arreglos=", arreglos);
console.log("...arreglos=", ...arreglos);
b = Math.min(...arreglos);
return b;
}
a = minimoAbsoluto(arreglosTest1, arreglosTest2);
console.log("a=", a);
Result
arreglos=
[[21,9,34],[9,8,13]]
...arreglos=
[21,9,34]
[9,8,13]
a=
NaN
That is to say that b = Math.min(...arreglos);
is being equivalent to b = Math.min([21,9,34],[9,8,13]);
which gives NaN
.
To concatenate the arrays (and then use the spread for Math.min
) there are several ways one is with reduce
var arreglosTest1 = [21, 9, 34],
arreglosTest2 = [9, 8, 13];
function minimoAbsoluto(...arreglos) {
var c = arreglos.reduce((acc, val) => [...acc, ...val]);
console.log(c);
var b = Math.min(...c);
return b;
}
a = minimoAbsoluto(arreglosTest1, arreglosTest2);
console.log("a=", a);
Another option is concat
var arreglosTest1 = [21, 9, 34],
arreglosTest2 = [9, 8, 13];
function minimoAbsoluto(...arreglos) {
var c = [].concat(...arreglos);
console.log(c);
var b = Math.min(...c);
return b;
}
a = minimoAbsoluto(arreglosTest1, arreglosTest2);
console.log("a=", a);
Another option, which even eliminates duplicates, is using sets
var arreglosTest1 = [21, 9, 34],
arreglosTest2 = [9, 8, 13];
function minimoAbsoluto(...arreglos) {
var c = [ ...new Set( [].concat(...arreglos) ) ];
console.log(c);
var b = Math.min(...c);
return b;
}
a = minimoAbsoluto(arreglosTest1, arreglosTest2);
console.log("a=", a);