- 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
Array of objects to array of arrays in JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"Date":"2014","Amount1":90,"Amount2":800}, {"Date":"2015","Amount1":110,"Amount2":300}, {"Date":"2016","Amount1":3000,"Amount2":500} ];
We are required to write a JavaScript function that takes in one such array and maps this array to another array that contains arrays instead of objects.
Therefore, the final array should look like this −
const output = [ ['2014', 90, 800], ['2015', 110, 300], ['2016', 3000, 500] ];
Example
The code for this will be −
const arr = [ {"Date":"2014","Amount1":90,"Amount2":800}, {"Date":"2015","Amount1":110,"Amount2":300}, {"Date":"2016","Amount1":3000,"Amount2":500} ]; const arrify = (arr = []) => { const res = []; const { length: l } = arr; for(let i = 0; i < l; i++){ const obj = arr[i]; const subArr = Object.values(obj); res.push(subArr); }; return res; }; console.log(arrify(arr));
Output
And the output in the console will be −
[ [ '2014', 90, 800 ], [ '2015', 110, 300 ], [ '2016', 3000, 500 ] ]
Advertisements