- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Map multiple properties in array of objects to the same array JavaScript
Suppose, we have an array of objects like this −
const arr = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6} ];
We are required to write a JavaScript function that takes in one such array of objects. The function should then map this array to an array of Number literals like this −
const output = [1, 2, 3, 4, 5, 6];
Example
const arr = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6} ]; const pushToArray = (arr = []) => { const result = arr.reduce((acc, obj) => { acc.push(obj.a); acc.push(obj.b); return acc; }, []); return result; }; console.log(pushToArray(arr));
Output
And the output in the console will be −
[ 1, 2, 3, 4, 5, 6 ]
Advertisements