-1

I have two arrays a and b like this:

const a = [1,2,3,4]
const b = ['1','2','3','4'] // could be 'a','b','c','d'

const reordered_a = [4,1,3,2] // based on this reordering 

function reorder_b() {
    // should return ['4','1','3','2']
} 

How can I return reordered version of b based on reordered positions in reordered_a?

Sara Ree
  • 3,417
  • 12
  • 48
  • `[...b].sort(mySortingFunction)` using [`Array.prototype.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – evolutionxbox Jan 03 '22 at 22:25
  • There are several ways to approach this. What have you tried? – charlietfl Jan 03 '22 at 22:25
  • Close voters please at least read the question you wanna close one time and mark is as duplicate ... same title of questions doesn't mean it's duplicated... – Sara Ree Jan 03 '22 at 22:36

2 Answers2

1

You could take an object with the indices for the values and map the pattern with the values of the indices.

const a = [1, 2, 3, 4]
const b = ['1', '2', '3', '4'] // could be 'a','b','c','d'

const reordered_a = [4, 1, 3, 2] // based on this reordering 

function reorder_b() {
   const references = Object.fromEntries(Object.entries(a).map(a => a.reverse()));
   return reordered_a.map(k => b[references[k]]);
}

console.log(reorder_b()); // 4 1 3 2
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
-1

What you got to do is first use every pair of elements el1 and el2 and convert them to numbers. Then once they're converted, make sure that the latter is bigger than the latter by checking their difference :

return b.sort((el1,el2)=>Number(el2)-Number(el1))
Fares
  • 893
  • 1
  • 11
  • 24