Checking for squared similarly of arrays in JavaScript


Problem

We are required to write a JavaScript function that takes in two arrays of numbers, arr1 and arr2, as the first and second argument respectively.

Our function should return true if and only if every element in arr2 is the square of any element of arr1 irrespective of their order of appearance.

For example, if the input to the function is −

Input

const arr1 = [4, 1, 8, 5, 9];
const arr2 = [81, 1, 25, 16, 64];

Output

const output = true;

Example

Following is the code −

 Live Demo

const arr1 = [4, 1, 8, 5, 9];
const arr2 = [81, 1, 25, 16, 64];
const isSquared = (arr1 = [], arr2 = []) => {
   for(let i = 0; i < arr2.length; i++){
      const el = arr2[i];
      const index = arr1.indexOf(el);
      if(el === -1){
         return false;
      };
   };
   return true;
};
console.log(isSquared(arr1, arr2));

Output

true

Updated on: 22-Apr-2021

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements