我有四个长度为18的数组(k1
、k2
、k3
和k4
(。我想比较每个数组的最后一个元素&复制具有最大final元素的数组的内容。
目前,我是这样做的:
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);
但这是不可扩展的,因为我将来会添加更多的阵列。
这里有另一种方法:
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);");
我听说eval((是一个主要的安全风险,有其他方法吗?
您可以使用排序并只返回descending sorted list
的第一个元素
const arr = [this.k1, this.k2, this.k3, this.k4]
// sort desc
const arrayHasMaxLastElement = arr.sort((a, b) => b[b.length - 1] - a[a.length - 1])[0]
使用reduce
获取最大项目的另一种方法
const arr = [[1,2,3], [3,4,5], [4,5,6], [7,8,9]];
const result = arr.reduce((max, item) => max.at(-1) > item.at(-1) ? max : item);
console.log(...result);
.as-console-wrapper{min-height: 100%!important; top: 0}