Squares of array items in JavaScript | Assignment Expert

Problem Statement:

We are given an array containing numbers and arrays of numbers. We need to create a new array by converting all numbers to their square forms. We need to convert all numbers including numbers inside arrays.

For example- converting [34, [76, 12, 54], [90, 45, 13, 95], 43, 33] => [ 1156, [ 5776, 144, 2916 ], [ 8100, 2025, 169, 9025 ], 1849, 1089 ]

Code for Squares of array items in JavaScript:

myArr = [34, [76, 12, 54], [90, 45, 13, 95], 43, 33];
for(let i=0; i<myArr.length; i++){
  if(typeof myArr[i]==='number'){
    myArr[i] = myArr[i]*myArr[i];
  }else{
    result = []
    for(let j=0;j<myArr[i].length;j++){
      result.push(myArr[i][j]*myArr[i][j]);
    }
    myArr[i] = result;
  }
}
console.log(myArr)

Output:

Output for Squares of array items in JavaScript

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@violet-cat-415996.hostingersite.com Thank you