Search code examples
javascriptarraysminmathjax

Math.min.apply(Math,Array) return NaN when Array.length = 100


when using the Math.min.apply and the Array.length is 10 is ok

getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
    indexes.push(i);
}
return indexes;
}

 arrayMinIndex(array) {
return this.getAllIndexes(array, Math.min.apply(Math,array));
}

enter image description here

but when the Arrays is more big in this case length = 100, the val is NaN,

enter image description here

UPDATE!!!!

if I change the index name of 00,01,02,03 ... 99 to 0,1,2,3,4 ... 99 its work

enter image description here

in this part I created the Array dynamically, the index name is a String. enter image description here

but for what the index name is problem to the MAth.min?


Solution

  • It seems when you are creating the array, you are creating keys like '01', '02' etc

    these are different to index 1 and 2

    See the following

    const array1 = new Array();
    const array2 = new Array();
    const array3 = new Array();
    array1[0] = 1;
    array2['00'] = 2
    array3[0] = 3
    array3['00'] = 4
    
    console.log(JSON.stringify(array1), typeof array1[0]);
    console.log(JSON.stringify(array2), typeof array2[0]);
    console.log(JSON.stringify(array3), typeof array3[0]);

    see how array2[0] is undefined ... now if you do

    const array = new Array();
    array['00'] = 10;
    array['01'] = 9;
    array['02'] = 8;
    array['03'] = 7;
    array['04'] = 6;
    array['05'] = 5;
    array['06'] = 4;
    array['07'] = 3;
    array['08'] = 2;
    array['09'] = 1;
    array['10'] = 100;
    console.log(array);

    look at all those undefined before index 10

    that's why Math.min results in NaN