
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reduce Array in JavaScript
Suppose, we have an array of objects like this −
const arr = [ {"time":"18:00:00"}, {"time":"10:00:00"}, {"time":"16:30:00"} ];
We are required to write a JavaScript function that takes in one such array and does the following −
Extract the times from the json code: so: 18:00:00, 10:00:00, 16:30:00
Convert the times to this: [18,0], [10,0], [16,30]
Put it in an array.
Return the final array.
Example
The code for this will be −
const arr = [ {"time":"18:00:00"}, {"time":"10:00:00"}, {"time":"16:30:00"} ]; const reduceArray = (arr = []) => { let res = []; res = arr.map(obj => { return obj['time'].split(':').slice(0, 2).map(el => { return +el; }); }); return res; }; console.log(reduceArray(arr));
Output
And the output in the console will be −
[ [ 18, 0 ], [ 10, 0 ], [ 16, 30 ] ]
Advertisements