2017-03-17 38 views
-3

给定一个混合元素数组,我的函数需要返回该数组中的最小数字。当数组中不存在数字时,函数应该返回'0'

要求:

  • 如果给定的数组是空的,它应该返回0。
  • 如果数组不包含的数字,它应该返回0。

我失败在数组不包含数字的情况下,通过测试应该返回0的测试。这里是我的代码:

function findSmallestNumberAmongMixedElements(arr) { 
 
    // your code here 
 
    if (arr.length === 0) return 0; 
 

 
    var shortest = arr.filter(function(a, b) { 
 
    return typeof a === 'number' && a - b; 
 
    }); 
 

 
    return Math.min.apply(null, shortest); 
 
} 
 

 
var output = findSmallestNumberAmongMixedElements(['string', 'string']); 
 
console.log(output); //=> Infinity (expected 0)

+1

请添加一些数据和想要的结果。 –

+0

请参阅http://stackoverflow.com/questions/42846325/function-getlargestelement-how-to-get-this-working-with-an-array-full-of-neg-n/42846433 - 交换<运算符。 –

+0

检查[this](http://stackoverflow.com/a/42846435/4543207)up – Redu

回答

0

你需要过滤

function findSmallestNumberAmongMixedElements(arr) { 
 
    // your code here 
 

 
    var shortest = arr.filter(function(a) { 
 
    return !isNaN(a); 
 
    }); 
 
    if (shortest.length === 0) return 0; 
 
    return Math.min.apply(null, shortest); 
 
} 
 

 
console.log(findSmallestNumberAmongMixedElements(["foo", "bar", 1])); 
 
console.log(findSmallestNumberAmongMixedElements(["foo", "bar"])); 
 
console.log(findSmallestNumberAmongMixedElements(["foo", "bar", 1, 2, 3])); 
 
console.log(findSmallestNumberAmongMixedElements(["foo", "bar", 4, 6, 7]));

注意,使用!isNaN()将转变为通过多项检查后的长度一个字符串 - >

console.log(findSmallestNumberAmongMixedElements(["foo", "bar", "4"]) // 4 

因此,保持你的支票

return typeof a === 'number' 

如果你想确保它作为一个数通过了数只 - >

console.log(findSmallestNumberAmongMixedElements(["foo", "bar", "4"]) // 0 
+0

这就是我最终做的。 – bsem

1

传递给filter功能并不需要两个参数。你应该先过滤您的阵列来获得number类型的唯一要素,然后使用三元运算符,如果该列表不为空,否则为零返回最低:

function findSmallestNumberAmongMixedElements(array) { 
 

 
    array = array.filter(function (e) { return typeof e === 'number' }) 
 

 
    return array.length ? Math.min.apply(null, array) : 0 
 
} 
 

 
console.log(
 
    findSmallestNumberAmongMixedElements(['10', 'the']) //=> 0 
 
) 
 

 
console.log(
 
    findSmallestNumberAmongMixedElements([10, 'the']) //=> 10 
 
)

+0

或者只是'返回Math.min.apply(null,array)|| 0' –

+0

我认为这也可以,但'Math.min.apply(null,[])'返回'Infinity'。 – gyre

-1

这将返回正确。

function findSmallestNumberAmongMixedElements(arr) { 
     var shortest = arr.filter(function (a, b) { 
      return typeof a === 'number' ? 0 : a - b; 
     }); 
     if (shortest.length === 0) return 0; 
     return Math.min.apply(null, shortest); 
    }