Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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]
Method 1: Using reduce()
The reduce() method can accumulate the original array and append squares:
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));
[ 12, 19, 5, 7, 9, 11, 21, 4, 144, 361, 25, 49, 81, 121, 441, 16 ]
Method 2: Using concat() with map()
A more readable approach combines the original array with mapped squares:
const arr = [12, 19, 5, 7, 9, 11, 21, 4];
const appendSquares = (arr) => {
const squares = arr.map(num => num * num);
return arr.concat(squares);
};
console.log(appendSquares(arr));
[ 12, 19, 5, 7, 9, 11, 21, 4, 144, 361, 25, 49, 81, 121, 441, 16 ]
Method 3: Using Spread Operator
The spread operator provides a modern, concise solution:
const arr = [12, 19, 5, 7, 9, 11, 21, 4];
const appendSquares = (arr) => {
return [...arr, ...arr.map(num => num * num)];
};
console.log(appendSquares(arr));
[ 12, 19, 5, 7, 9, 11, 21, 4, 144, 361, 25, 49, 81, 121, 441, 16 ]
Comparison
| Method | Readability | Performance | Modern Syntax |
|---|---|---|---|
reduce() |
Medium | Good | ES6 |
concat() + map() |
High | Good | ES5+ |
| Spread Operator | High | Good | ES6 |
Conclusion
The spread operator method offers the cleanest syntax for appending squared values. Use concat() + map() for better readability in complex scenarios.
Advertisements
