1

I have a variable dimensions, which contains the maximum size of each element of an array, e.g.:

const dimensions = [10, 6, 4]

I also have an array of arrays containing as many integers as the size of the dimensions array, e.g.:

let boxes = [
    [1, 2, 1],
    [10, 2, 4],
    [4, 1, 1],
    [10, 2, 3]
]

For every array in boxes, no element will be higher than its counterpart in dimensions.

I want to find a way to sort these arrays, so that the sorted array boxes would be:

[
    [1, 2, 1],
    [4, 1, 1],
    [10, 2, 3],
    [10, 2, 4]
]

As you see, it's not just about sorting by the array's first element. It's sorting by first element, and if they're equal, the second, etc.

For each array of arrays, I have a related dimensions variable. But dimensions can be anything (also any length!) (and consequently, the arrays will have the same length of course).

I'm doing this in Javascript, but pseudocode is welcome too.

PS - This is not part of an assignment, I tried to abstract away most of the unnecessary stuff.

1 Answer 1

1

You can sort the values using Array.reduce to compare the values in each array being sorted, only updating the comparison result if it is currently 0 (i.e. the values up to now have been equal):

let boxes = [
  [1, 2, 1],
  [10, 2, 4],
  [4, 1, 1],
  [10, 2, 3]
]

boxes.sort((a, b) => a.reduce((c, v, i) => c ? c : v - b[i], 0));

console.log(boxes);

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

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.