Answer to Question #177719 in HTML/JavaScript Web Application for adhi chinna

Question #177719

given myArray of numbers, write a function to square the alternate numbers of the myArray, starting from index 0 using the array method map.Input

  • input will be a single line containing  myArray

Output

  • output should be a single line containing an array with alternate numbers squared

Constraints

  • Each value in the array must be a number

1 Input

[ 1, 2, 3, 4, 5 ]

1 Output

[ 1, 2, 9, 4, 25 ]

2 Input

[ 2, 4 ]

2 Output

[ 4, 4 ]

"use strict";

process.stdin.resume();

process.stdin.setEncoding("utf-8");

let inputString = "";

let currentLine = 0;

process.stdin.on("data", (inputStdin) => {

 inputString += inputStdin;

});

process.stdin.on("end", (_) => {

 inputString = inputString.trim().split("\n").map((str) => str.trim());

 main();

});

function readLine() {

 return inputString[currentLine++];

}

/*not modify above this line */

function main() {

 const myArray = JSON.parse(readLine());

 /* Write your code here */


1
Expert's answer
2021-04-03T04:15:40-0400

let array = [1,2,3,4,5];


function square(arr){

      let newArr = [];

      for(var i = 0 ; i < arr.length; i++){

            newArr.push(arr[i++]);

      }

      let mappedArr = arr.map((num) =>{

            for(let i = 0; i < newArr.length; i++){

                  if(num === newArr[i]){

                        num = num**2;

                  }

            }

            return num;

      });

      console.log(mappedArr);

}

square(array);


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS