Append the current array with the squares of corresponding elements of the array in JavaScript


We have an array of Numbers like this −

const arr = [12, 19, 5, 7, 9, 11, 21, 4];

We have to write a function that takes in such an array and returns a new array with all the items of the original array appended by the squares of corresponding elements of the array.

For this sample array, the output should be −

[12, 19, 5, 7, 9, 11, 21, 4, 144, 361, 25, 49, 81, 121, 441, 16]

Example

const arr = [12, 19, 5, 7, 9, 11, 21, 4];
const multiplyArray = (arr) => {
   return arr.reduce((acc, val) => {
      return acc.concat(val * val);
   }, arr);
};
console.log(multiplyArray(arr));

Output

The output in the console will be −

[
   12, 19, 5, 7, 9, 11,
   21, 4, 144, 361, 25, 49,
   81, 121, 441, 16
]

Updated on: 21-Aug-2020

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements