Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to verify if the values in the second array correspond to the square values of the first array using Javascript

I have problem with the if-else statement and also splice seems to be not working.

function same(arr1, arr2) {
    if (arr1.length !== arr2.length) {
        return false;
    }
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            let correctIndex = arr1[i] * 2;
            if (correctIndex !== arr2[j]) {
                return false;
            }
        }
        console.log(arr2);
        arr2.splice(correctIndex, 1)
    }
    return true;
}

same([1, 2, 3, 2], [9, 1, 4, 4]);
like image 778
H_B Avatar asked Feb 12 '26 04:02

H_B


1 Answers

try this:

const sortNumber = numArray => numArray.sort((a, b) => a - b);

const same = (_arr1, _arr2) => { 
    const arr2 = sortNumber(_arr2);
    return sortNumber(_arr1).every((res,i)=>arr2[i]===res**2);
}

console.log(same([1, 2, 3, 2], [9, 1, 4, 4]))
like image 153
Ghoul Ahmed Avatar answered Feb 14 '26 17:02

Ghoul Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!