I’ve four arrays of length 18 (k1
,k2
,k3
&k4
). I want to compare the last element of each array & copy the contents of the array with the largest final element.
Currently, this is how I’m doing it:
if (this.k4[17]>=this.k1[17] && this.k4[17]>=this.k2[17] && this.k4[17]>=this.k3[17])
m = this.k4.filter(() => true);
else if(this.k1[17]>=this.k4[17] && this.k1[17]>=this.k2[17] && this.k1[17]>=this.k3[17])
m = this.k1.filter(() => true);
else if(this.k2[17]>=this.k4[17] && this.k2[17]>=this.k1[17] && this.k2[17]>=this.k3[17])
m = this.k2.filter(() => true);
else
m = this.k3.filter(() => true);
But this isn’t scalable incase I added more arrays in the future.
Here is another method:
var maxlast = [this.k1[17],this.k2[17],this.k3[17],this.k4[17]];
var max = maxlast.reduce(function(a,b){return Math.max(a, b)}, -Infinity);
var pos = maxlast.indexOf(max)+1;
m = eval("this.k"+pos+".filter(() => true);");
I’ve heard eval() is a major security risk, is there an alternative approach?