Check if 2 arrays have the identical values (second array is squared representation of numbers in the first array)
function same (arr1, arr2) {
if (arr1.length !== arr2.length) return false
const getFrequencyObject = (arr) => {
return arr.reduce((acc, value) => {
acc[value] = acc[value] ? ++acc[value] : 1
return acc
}, {})
}
const frequencyCounter1 = getFrequencyObject(arr1)
const frequencyCounter2 = getFrequencyObject(arr2)
for(const key in frequencyCounter1) {
// the squared number from arr1 should be as a value in arr2
if (!(key ** 2 in frequencyCounter2)) return false
// the value frequency in arr2 should be the same as in arr1
if (frequencyCounter2[key ** 2] !== frequencyCounter1[key]) return false
}
return true
}
console.log(same([2, 4, 6, 8], [16, 36, 4, 64])) // true
console.log(same([2, 4, 6, 8], [16, 36, 4, 65])) // false