Here is the question
Q) take 2 arrays and pass it to a function, then check if the square of the array1 is contained in the array2 (Note: Order doesn't matter, also 2 duplicates in arr1[1,2,2], there should be 2 duplicates in arr2[1,4,4]).
I have this code in which, i am trying to convert the indexOf to a for loop and i have included that code which i tried after this code
function same2(arr1, arr2){
if (arr1.length !== arr2.length){
return false;
}
for (let i = 0; i < arr1.length; i++){
let currentIndex = arr2.indexOf(arr1[i] ** 2);
// if the square of arr1 is contained in any of the index in arr2
if (currentIndex === -1){
return false;
}
console.log(arr2);
arr2.splice(currentIndex, 1);
}
return true;
}
same2([10,2, 3, 5], [100, 4, 25, 9]);
Here is the code with 2 for loop and its giving wrong output for the corresponding input.
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 currentIndex = arr1[i] ** 2;
console.log(currentIndex);
if (currentIndex === -1){
return false;
}
if (arr2[j] === currentIndex){
arr2.splice(currentIndex, 1);
// console.log(arr2);
}
}
}
return true;
}
same([1, 10,2, 4], [10, 1, 16, 4]);
I know i have problem with the index of the array, but i am not able to break it.