sha*_*ran 4 javascript arrays reduce list flatten
我试图在输入中展平数组数组,并返回最长的字符串.
例如,给定输入:
i = ['big',[0,1,2,3,4],'tiny']
Run Code Online (Sandbox Code Playgroud)
该函数应返回'tiny'.我想使用reduce或concat以原生和优雅的方式解决这个问题(没有在数组中实现flatten原型)但我没有使用这段代码:
function longestStr(i)
{
// It will be an array like (['big',[0,1,2,3,4],'tiny'])
// and the function should return the longest string in the array
// This should flatten an array of arrays
var r = i.reduce(function(a, b)
{
return a.concat(b);
});
// This should fetch the longest in the flattened array
return r.reduce(function (a, b)
{
return a.length > b.length ? a : b;
});
}
Run Code Online (Sandbox Code Playgroud)
您的问题是您忘记将initialValue参数传递给reduce函数,在这种情况下,reduce函数必须是数组.
var r = i.reduce(function(a, b) {
return a.concat(b);
}, []);
Run Code Online (Sandbox Code Playgroud)
如果没有提供initialValue,将a用于第一次调用值将是第一个元素i数组,这是串大你的情况,那么你将被调用String.prototype.concat函数代替Array.prototype.concat.
这意味着最后,r是一个字符串,字符串没有reduce函数.
但是,您的解决方案可以简化:
['big',[0,1,2,3],'tiny'].reduce(function longest(a, b) {
b = Array.isArray(b)? b.reduce(longest, '') : b;
return b.length > a.length? b : a;
}, '');
Run Code Online (Sandbox Code Playgroud)