我有一个包含3个元素的数组。
var arr = [-1,2,-1];
如何在数组中找到最小值,当我想忽略数组中的'-1'时,无论其位置如何。
var arr = [-1,1,3]; //should give 1
var arr = [-1,2,-1]; //should give 2
var arr = [1,0,-1,4,5,2]; //should give 0
答案 0 :(得分:2)
您可以过滤值并从中获取最小值。
var array = [1, 0, -1, 4, 5, 2],
min = Math.min(...array.filter(a => a !== -1));
console.log(min);
答案 1 :(得分:0)
使用Array#reduce
方法
var arr = [-1, 1, 0, -1, 4, 5, 2];
console.log(
// iterate and comare values
arr.reduce(function(a, b) {
// compare the values
return (a === null || b < a) && b > -1 ? b : a;
// set initial value as null to avoid selecting -ve value
// in case all values are negative
}, null)
)
// with ES6 arrow function
console.log(
arr.reduce((a, b) => (a === null || b < a) && b > -1 ? b : a, null)
)
var arr = [-1, 1, 3]; //should give 1
var arr1 = [-1, 2, -1]; //should give 2
var arr2 = [1, 0, -1, 4, 5, 2];
console.log(
arr.reduce((a, b) => (a === null || b < a) && b > -1 ? b : a, null)
)
console.log(
arr1.reduce((a, b) => (a === null || b < a) && b > -1 ? b : a, null)
)
console.log(
arr2.reduce((a, b) => (a === null || b < a) && b > -1 ? b : a, null)
)
答案 2 :(得分:-2)
您是否尝试从阵列中删除负数?
const newArr = arr.filter(num => num >= 0)