0

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.

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)

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.

There is a better and fast way to achieve the same result?

J

7
  • Could you give some more examples? Also your array looks like it may be 3D? (there are three [, maybe that is just an error) Commented Dec 8, 2016 at 22:55
  • Confusing on many levels but Isn't it 1,1,1,2,2,2,3,4 for the second argument? (i.e. last 4 missing) Commented Dec 8, 2016 at 23:03
  • I can't understand what you're doing at all. When you say "1st argument" and "2nd argument", do you mean 1st and 2nd elements of the inner arrays? Commented Dec 8, 2016 at 23:05
  • based on what array? What is the highest value versus what in your array sample according to you - there's no help possible without, us, understanding that. Commented Dec 8, 2016 at 23:19
  • Do you want the maximum first element, or the last 1st element in the array when where the 2nd element <= number? Or are they the same because the first element is sorted? Commented Dec 8, 2016 at 23:27

3 Answers 3

1

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, e.g. 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.

You state that you could use for loops to solve the problem. 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:

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.

In addition, you mention that

the dimension of the arr is not fixed

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(). 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]]
));

Sign up to request clarification or add additional context in comments.

3 Comments

Tnx, i think you got the point, you make a new array with the 2 result's with I need. I don't really know yet if I need to start with an array like this, maybe I make a single array, so var arr = [[1,1],[2,1],[3,1],[4,2],[5,2],[6,2],[7,3],[8,4]] In this case I can always use your solution?
Sure. Then you don't need the outer loop.
@JormanFranzini, I updated the answer to demonstrate how you can use my solution for a single array. Hope this answers your question.
0

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.

e.g.

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;
});

2 Comments

Tnx, but if the number is not on array? I mean If my number is 2 and the arr is [[1,4],[2,1],[3,1],[4,3],[5,3],[6,3],[7,3],[8,4]] my goal is to take 3, not 1
So the "2" in your example relates to the Index? Arrays in JS start at 0, so the 2nd entry needs to be 1
0

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

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). 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.