Balancing two arrays in JavaScript


Problem

We are required to write a JavaScript function that takes in two arrays of numbers, arr1 and arr2, as the first and the second argument.

The sum of elements in arr1 and arr2 are different. Our function should pick one element from the first array and push it in the second array and pick one element from the second array and push it in the first array such that the sum of the elements of both the arrays become equal. We should return an array of these two elements.

For example, if the input to the function is

Input

const arr1 = [1, 2, 5];
const arr2 = [2, 4];

Output

const output = [5, 4];

Output Explanation

Because if we remove 5 from arr1 and push it to arr2 and remove 4 from arr2 and push it to arr1 then the sum of both the arrays will be equal (7).

Following is the code:

Example

const arr1 = [1, 2, 5];
const arr2 = [2, 4];
const balanceArrays = (arr1 = [], arr2 = []) => {
   const sumA = arr1.reduce((acc, v) => acc + v, 0)
   const sumB = arr2.reduce((acc, v) => acc + v, 0)
   const difference = (sumA + sumB) / 2 - sumA
   const map = arr2.reduce((acc, v) => {
      acc[v] = true
      return acc
   }, {})
   for(let i = 0; i < arr1.length; i++) {
      if(map[arr1[i] + difference] === true) {
         return [arr1[i], arr1[i] + difference]
      }
   }
   return []
};
console.log(balanceArrays(arr1, arr2));

Output

[5, 4]

Updated on: 23-Apr-2021

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements