Maximize first array over second in JavaScript


Problem

We are required to write a JavaScript function that takes in two arrays of numbers, arr1 and arr2, of the same length.

Our function should shuffle the elements of the first array, arr1, such that its maximum number of elements are greater than corresponding elements of the array arr2. The function should then return the shuffled array.

For example, if the input to the function is

Input

const arr1 = [3, 5, 12, 19];
const arr2 = [2, 9, 3, 12];

Output

const output = [3, 12, 5, 19];

Output Explanation

Before shuffling arr1, it had 3 corresponding elements greater than that of arr2, but in the shuffled array, all 4 elements are greater.

Following is the code:

Example

 Live Demo

const arr1 = [3, 5, 12, 19];
const arr2 = [2, 9, 3, 12];
const maximiseArray = (arr1 = [], arr2 = []) => {
   arr1.sort((a, b) => b - a)
   const indexes = arr2.map((v, index) => index).sort((a, b) => arr2[b] - arr2[a])
   const res = []
   for(let i = 0; i < indexes.length; i++) {
      const index = indexes[i]
      res[index] = arr1[0] > arr2[index] ? arr1.shift() : arr1.pop()
   }
   return res
}
console.log(maximiseArray(arr1, arr2));

Output

[ 3, 12, 5, 19 ]

Updated on: 23-Apr-2021

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements