0

so I have two arrays - arrOne = [10, 2, 3, 14, 1] and arrTwo = [1, 2, 3, 5, 4];

I want sort the arrTwo and use the same indexing changes on arrOne, ie arrTwo = [1, 2, 3, 4, 5], arrOne [10, 2, 3, 1, 14].

I've been trying to implement it with merge sort, but it does not work. The recursion obstructs me from doing what I intended.

Important to note, I am getting the data as two integers at a time and push them into separate arrays, using the previous arrays that would mean -

  1. input 10 ,1
  2. input 2, 2
  3. input 3, 3
  4. input 14, 5
  5. input 1, 4

Perhaps a different data structure could be used, but I am not aware of it.

I have put go as a tag since I would like to solve it both languages.

0

2 Answers 2

1

Create a 2d array which holds value of 2 arrays and extract 2 arrays after sorting.

let arrOne = [10, 2, 3, 14, 1],
  arrTwo = [1, 2, 3, 5, 4];



arrOne
  // create 2d array which contains both array values
  .map((v, i) => [v, arrTwo[i]])
  // sort the combined array based on first array element
  .sort(([a], [b]) => a - b)
  // update the main arrays
  .forEach(([v1, v2], i) => {
    arrOne[i] = v1;
    arrTwo[i] = v2;
  })

console.log(arrOne, arrTwo)

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

2 Comments

Nice answer to the sorting of two arrays 👍 my answer is based on the usage of two arrays not really being the right data structure for this.
awesome stuff, just have to figure out how to get this done in Go. thanks Pranav!
0

To solve this I would not use two arrays.

I would push an object to a single array. Making it much more structured keeping the data “together”


const data = [{
 one: 10,
 two: 1
},
{
 one: 2,
 two: 2
},

{
 one: 3,
  two: 3
},

{
 one: 14,
 two: 5
},
{
 one: 1,
 two: 4
}

To add another input:

data.push({
   one: 200,
   two: 6
})

Then sort by key “two”

data.sort((a, b) => {
    return a.two-b.two
})

Just note that the sort will mutate the array but you can copy if this is an issue. Guessing sorting the original array is not a problem for your use case anyway.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.