skip to Main Content

I have two arrays:

arr1 = [4,2,3,5,1]
arr2 = ['a','b','c','d','e']

And if I apply an sorting algorithm to arr1, (e.g. by smaller number) it should update the indexes in the same way on arr2 (if arr1’s 4, before in index 0 gets moved to index 3, arr2’s value in index 0 gets moved to index 3).

ex.

arr1 = [1,2,3,4,5]
arr2 = ['e','b','c','a','d']

I’ve tried working with the JS sort function to no avail. Because the numbers in the arrays may be duplicates, indexOf() doesn’t work. I don’t feel I need to implement my own sorting algorithm because I really feel like an elegant way is possible here.

2

Answers


  1. Using an extra array should work for you something like this:

    const arr3 = arr1.map((elem,index) => { return [arr1[index], arr2[index]] }).sort((a,b) => a[0] - b[0]); //b-a for desc
    
    arr1 = arr3.map((elem,index) => { return arr3[index][0] });
    arr2 = arr3.map((elem,index) => { return arr3[index][1] });
    Login or Signup to reply.
  2. You can achieve this by combining Array 1 and Array 2 to one single array and then sorting the combined array by the values of array one.

    Refer the code below :

    function customSort(arr1, arr2) {
      // Combine arr1 and arr2 into an array of objects
      const combinedArray = arr1.map((value, index) => ({ value, arr2Value: arr2[index] }));
    
      // Sort the combined array based on the values in arr1
      combinedArray.sort((a, b) => a.value - b.value);
    
      // Update arr1 and arr2 based on the sorted order
      for (let i = 0; i < arr1.length; i++) {
        arr1[i] = combinedArray[i].value;
        arr2[i] = combinedArray[i].arr2Value;
      }
    }
    
    const arr1 = [4, 2, 3, 5, 1];
    const arr2 = ['a', 'b', 'c', 'd', 'e'];
    
    customSort(arr1, arr2);
    
    console.log('Sorted arr1:', JSON.stringify(arr1));
    console.log('Corresponding arr2:', JSON.stringify(arr2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search