0

hope you can help me fix this.

So I have one array with nested arrays:

mainArr: [[Carl, 20, Male],[Mike, 30, Male], [Chloe, 45, Female], ...]

Now this array needs to be sorted along another array containing a set order of indexes from the array above.

indexArr: [2,1,3,...]

Result here being:

sortedArr: [[Mike, 30, Male], [Carl, 20, Male], [Chloe, 45, Female], ...]

I thought about writing a ForEach loop with the second array, something along the lines of:

indexArr.forEach(i){
 sortedArr.push(mainArr[indexArr[i]]);
};

But I'm trying to avoid using loops with this function to keep it fast. I couldn't find anything relevant to my problem in any array documentation. Do you know a way to fill sortedArr or sort mainArr efficiently?

2
  • Don't think there's anything faster than your forEach loop Commented Oct 22, 2021 at 19:19
  • 1
    You can't do this without iterating over the entries in the array (whether that's an explicit for/foreach loop or an implicit loop such as map). Commented Oct 22, 2021 at 19:26

1 Answer 1

4
    indexArr.map(ind => mainArr[ind - 1])
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect, should've thought of that! Thanks alot
good answer using a loop, which is necessary
Each read with the array of positions, e.g. const item = mainArr[sortArr[index]] will have a constant number of steps (O(1) complexity). Still, you will need to go through the entire array for picking up all the items, an action whose number of steps increases as you have more items (O(n) complexity, which is what you're attempting to void). In this sense, I see no way out of looping to obtain all the items you need, regardless of the array method you use (e.g., this map will not avoid looping through the items), with no complexity difference - push or this approach will be O(1).
I've realized you're right, there's no way escaping the loop in this. It'll have to do!

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.