# Rearranging elements of an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

The array arr, will always be of even length.

Our function should return true if and only if it is possible to reorder it such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < length(arr) / 2.

For example, if the input to the function is −

const arr = [4, -2, 2, -4];

Then the output should be −

const output = true;

## Output Explanation

We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].

## Example

The code for this will be −

Live Demo

const arr = [4, -2, 2, -4];
const canRearrange = (arr = []) => {
const map = arr.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1
return acc
}, {});
const keys = Object.keys(map)
.map(key => Number(key))
.sort((a, b) => a - b)
for (const key of keys) {
if (key < 0) {
while (map[key] > 0) {
if (map[key / 2] > 0) {
map[key] -= 1
map[key / 2] -= 1
} else {
return false
}
}
} else {
while (map[key] > 0) {
if (map[key * 2] > 0) {
map[key] -= 1
map[key * 2] -= 1
} else {
return false
}
}
}
}
return true
};
console.log(canRearrange(arr));

## Output

And the output in the console will be −

true
Updated on 09-Apr-2021 09:18:11