简体   繁体   English

Javascript根据数组本身在2D数组中找到最大值

[英]Javascript find the highest value in 2d array based on array itself

I've a multidimensional array 我有一个多维数组

arr = [[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]],
       [[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]]
      ];

and so on ... but the dimension of the arr is not fixed, is variable. 依此类推...但是arr的尺寸不固定,是可变的。

I've a variable that tell me where to point my attention 我有一个变量,告诉我要注意的地方

var number = 2;

So my goal is the look in any arr[i] and find the max 1st argument based on the 2nd argument, I try to explain better my self, in this particular case if number is 2 my expectation is to have from arr: for the 1st array in arr -> 6 (because the second argument is 1,1,1,2,2,2,3 so I've to point at the last 2 and return the 1st argument) for the 2nd array in arr -> 3 (because 2 is missing and the 1 is the last second argument) 因此,我的目标是在任意arr [i]中查找并根据第二个参数找到最大的第一个参数,我试图更好地解释自己,在这种情况下,如果数字为2,我期望从arr获得: arr->中第二个数组的arr-> 6中的第一个数组(因为第二个参数是1,1,1,2,2,2,3,所以我必须指向最后一个2并返回第一个参数) 3(因为缺少2,而1是最后一个第二个参数)

I know is a little tricky 我知道有点棘手

My first idea was to make a for loops where I delete all value over my number, then I can take the very last one, but I think I'm over-complicating all. 我的第一个想法是创建一个for循环,其中删除数字中的所有值,然后再取最后一个值,但是我认为所有操作都过于复杂了。

There is a better and fast way to achieve the same result? 有没有更好更快的方法来达到相同的结果?

J Ĵ

You present lists (arrays) of pairs of numbers, where the pairs are sorted in ascending order, first by the second number, then by the first. 您将显示数字对的列表(数组),其中对以升序排列,首先是第二个数字,然后是第一个。

What you seem to ask for is: Given a number to search for among the second numbers, eg number = 2 , find the last pair where the second number is less than or equal to this number, and return the corresponding first number in this pair. 您似乎想要的是:给定一个要在第二个数字中搜索的数字,例如number = 2 ,找到第二个数字小于或等于该数字的最后一个对,然后返回该对中的相应第一个数字。

You state that you could use for loops to solve the problem. 您声明可以使用for循环来解决问题。 A straightforward approach could be like the following snippet: 一种简单的方法可能类似于以下代码段:

 var arr = [[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]], [[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]] ]; var findNumber = 2; var result = []; for(var i = 0; i < arr.length; i++){ var maxIndex = -1; for(var j = 0; j < arr[i].length && arr[i][j][1] <= findNumber; j++){ maxIndex = j; } result.push(arr[i][maxIndex][0]); } //gives the expected answers 6 and 3 console.log(result); 

Then you ask: 然后您问:

There is a better and fast way to achieve the same result? 有没有更好更快的方法来达到相同的结果?

A solution involving .map and .reduce could be considered more elegant, like the following: 涉及.map.reduce解决方案可能被认为更优雅,如下所示:

 var arr = [[[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]], [[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]] ]; var findNumber = 2; var result = arr.map(function(val){ return val[val.reduce(function(acc, curr, index){ return curr[1] <= findNumber? index : acc; }, -1)][0]; }); //gives the expected answers 6 and 3 console.log(result); 

However, in terms of performance, for loops are likely to perform better (run faster) and are easy to comprehend. 但是,就性能而言, for循环可能会执行得更好(运行得更快)并且易于理解。

In addition, you mention that 另外,您提到

the dimension of the arr is not fixed arr的尺寸不固定

You would need to post some code examples on how the dimensionality of your data may vary before it would be possible to provide any answer that handles this aspect. 您可能需要发布一些代码示例,说明数据的维数如何变化,然后才可能提供处理此方面的任何答案。

Update 更新资料

To handle a single array of pairs, you do not need the outer loop or .map() . 要处理单对数组,不需要外部循环或.map() Putting the solution above into a reusable function: 将以上解决方案放入可重用的函数中:

 function lookupFirstNumberFromSecond(secondNumberToFind, arr){ var j = 0, maxIndex = -1; while(j < arr.length && arr[j][1] <= secondNumberToFind){ maxIndex = j++; } return arr[maxIndex][0]; } //gives the expected answer 6 console.log(lookupFirstNumberFromSecond( 2, [[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]] )); //gives the expected answer 3 console.log(lookupFirstNumberFromSecond( 2, [[1,1],[2,1],[3,1],[4,3],[5,3],[6,4],[7,4],[8,5],[9,5],[10,5]] )); 

I'm not entirely sure about what you are trying to achieve but I guess Array.reduce is a pretty elegant solution to get a single value out of an array. 我不确定您要实现的目标,但是我想Array.reduce是从数组中获取单个值的一种非常优雅的解决方案。

eg 例如

var number = 2;
[[1,4],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]]
.reduce(function (a, b) {
   return ((!a || b[0] > a[0]) && b[1] === number) ? b : a;
});

Not entirely sure what you're trying to solve either, but if you're trying to get the max value in a n dimensional array, then the most straightforward method is to solve this standardly in a recursive manner 不能完全确定您要解决的问题,但是如果要获取n维数组中的最大值,那么最直接的方法是以递归方式标准地解决此问题

function recurseMax(arr) {
    if (Number.isInteger(arr)) {
        return arr;
    }
    else {
        answer = 0;
        for (let i = 0; i < arr.length; i++) {
            answer = answer > recurseMax(arr[i]) ? answer : recurseMax(arr[i]);
        }
        return answer;
    }
}
console.log(recurseMax([1,[3, 5], [5, 6, 7, 10], [2, [3, [500]]]])); //Outputs 500

For each element, either is a number or another possible multidimensional element, so we recursively find its max. 对于每个元素,要么是一个数字,要么是另一个可能的多维元素,因此我们递归地找到其最大值。 This avoids potential overhead from a reduce operation (though I'm not experienced enough to speak with confidence whether or not it is completely faster, not really sure of the optimizations V8 can do on reduce or a plain old recursion loop). 这避免了来自reduce操作的潜在开销(尽管我没有足够的经验来自信地说它是否完全更快,还不确定V8在reduce或普通的旧递归循环上可以进行的优化)。 Either way, the solution is fairly straightforward. 无论哪种方式,解决方案都非常简单。

I am answering the question based on the assumption that you mean that the array can have a max dimension of n . 我在回答这个问题时所基于的假设是,您的意思是数组的最大维数为n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM