0

I got two arrays:

let arrayValues = [["20", "."], ["42", "."], ["44", "."], ["6", "."], ["5", "."]]
let arrayIndex = [4,5,1,2,3]

and I got one Problem:

I'd like to sort the values array based on the numbers of the index Array - (note that the first Element is connected to the first Element, the second one to the second and so on) - so that the highest number comes first, the second next and so one. This order needs to be translated to the first array.

The result should be this:

let result = ["42", "."], ["20", "."], ["5", "."], ["6", "."], ["44", "."]]

because of the new order

= [5,4,3,2,1]

I now my question deals with a super special problem - but I got no idea how to start tbh.

Any help would be really appreciated.

Heres my python code:

arrayValues = (("20", "."), ("42", "."), ("44", "."), ("6", "."), ("5", "."))
arrayIndex = (4,5,1,2,3)
result = sorted(range(len(arrayValues)), key=lambda i:arrayIndex[i],reverse=0)
1
  • 1
    What have you tried so far? And remember that "sorting" doesn't need to be in place. Building a new array and throwing away the old one(s) is usually perfectly fine. Commented Jul 9, 2019 at 17:51

2 Answers 2

1

You could get the indices, soert them by the values at this index and map the values in the new order.

var values = [["20", "."], ["42", "."], ["44", "."], ["6", "."], ["5", "."]],
    order = [4, 5, 1, 2, 3],
    result = [...order.keys()]
        .sort((a, b) => order[b] - order[a])
        .map(i => values[i]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

0

You can just take the indices:

  const result = [];

  for(let i = 0; i < arrayValues.length && i < arrayIndex.length; i++)
    result[ arrayIndex[i] - 1 ] = arrayValues[i];

Comments

Your Answer

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