Online Node.js Compiler

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));