I have created a programme that checks if the 2nd array is square of the 1st array or not. In the programme, I used a square variable double and sorted elements and check with the target that both were the same or not; if they were the same, it returned true. But what is the missing part? Could you please check and rectify that?
function compareSqr(nums, target) {
let square = nums.map((num) => num * num).sort((a, b) => (a - b));
if (square == target) {
return true
} else {
return false
}
}
console.log(compareSqr([1, 2, 3, 4], [1, 4, 9, 16]))
You are trying to compare two object, but if they do not share the same object reference then you get different objects.
Better compare the array with their values.
function compareSqr(values, squares) {
return values.every((value, index) => value ** 2 === squares[index]);
}
console.log(compareSqr([1, 2, 3, 4], [1, 4, 9, 16]));