[英]What's the best way to find the shortest array in a two dimensional array?
Say for example I have an array that looks like this:比如说我有一个看起来像这样的数组:
var myArray = [[1,2,3],[1,2,3,4],[1,2],[1,2]];
I'm trying to find the first shortest array inside myArray
which in this case would be myArray[2]
.我试图在
myArray
中找到第一个最短的数组,在本例中为myArray[2]
。
Obviously I could just write a loop, checking the length of each array and returning the smallest one.显然我可以只写一个循环,检查每个数组的长度并返回最小的一个。 What I'm wondering is if there's a really clean or cleaver way to do it in javascript. Something along the lines of this: http://ejohn.org/blog/fast-javascript-maxmin/
我想知道的是,在 javascript 中是否有一种真正干净或切肉刀的方法来做到这一点。大致如下: http://ejohn.org/blog/fast-javascript-maxmin/
Thanks!谢谢!
Well you could do it like this:那么你可以这样做:
var shortest = myArray.reduce(function(p,c) {return p.length>c.length?c:p;},{length:Infinity});
This uses an internal loop so it's faster than manually running your own loop, but would require a shim to work in older browsers.这使用内部循环,因此它比手动运行您自己的循环要快,但需要垫片才能在较旧的浏览器中工作。
The way you are looking for using max or min looks like this.您正在寻找使用 max 或 min 的方式如下所示。
Math.max.apply(Math, $.map(array, function (index) { return index.length }));
The trick is mapping to the inner arrays length attribute.诀窍是映射到内部数组的长度属性。
If by best you mean fastest time.. You will not achive a solution that is better than O(N), since you must check each element in the array (assuming it is unsorted).如果最好的意思是最快的时间.. 你不会得到比 O(N) 更好的解决方案,因为你必须检查数组中的每个元素(假设它是未排序的)。
Since you cannot achieve anything better than O(N), I see no reason not to do something like the following:由于您无法实现比 O(N) 更好的目标,因此我认为没有理由不执行以下操作:
var myArray = [[1,2,3],[1,2,3,4],[1,2],[1,2]];
var shortestIndex = 0;
for( var i=1; i< myArray.length; i++){
if(myArray[shortestIndex].length > myArray[i].length)
shortestIndex = i;
}
now myArray[shortestIndex]
is the shortest array.现在
myArray[shortestIndex]
是最短的数组。
Using javascript array reduce
.使用 javascript 数组
reduce
。 Remember that a reducer will only return one value, we will be reducing the array into a value.请记住,reducer 只会返回一个值,我们会将数组缩减为一个值。
reduce(callback,initialValue)
JavaScript invokes the callback function upon each item of the array JavaScript 对数组的每一项调用回调 function
const findShortestArray = (arr = []) => {
// we iterate over array and "val" is the current array element that we are on
// acc is the current result so far
const res = arr.reduce((acc, val, index) => {
if (!index || val.length < acc[0].length) {
return [val];
}
if (val.length === acc[0].length) {
acc.push(val);
}
return acc;
// initial value=[]
}, []);
return res;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.