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
Reduce array in JavaScript
In JavaScript, arrays can be transformed using various methods. This article demonstrates how to extract and convert time values from an array of objects into a more usable format.
Suppose we have an array of objects containing time strings:
const arr = [
{"time":"18:00:00"},
{"time":"10:00:00"},
{"time":"16:30:00"}
];
We need to create a function that:
Extracts the time strings from each object
Converts times like "18:00:00" to arrays like [18, 0]
Returns an array containing all converted time arrays
Using map() to Transform Array Elements
The map() method creates a new array by transforming each element. Here's our solution:
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));
[ [ 18, 0 ], [ 10, 0 ], [ 16, 30 ] ]
How It Works
The function processes each object through these steps:
-
obj['time']- extracts the time string -
.split(':')- splits "18:00:00" into ["18", "00", "00"] -
.slice(0, 2)- takes only first two elements ["18", "00"] -
.map(el => +el)- converts strings to numbers [18, 0]
Simplified Version
We can make this more concise by removing the intermediate variable:
const arr = [
{"time":"18:00:00"},
{"time":"10:00:00"},
{"time":"16:30:00"}
];
const reduceArray = (arr = []) => {
return arr.map(obj =>
obj.time.split(':').slice(0, 2).map(Number)
);
};
console.log(reduceArray(arr));
[ [ 18, 0 ], [ 10, 0 ], [ 16, 30 ] ]
Alternative: Using Destructuring
For even cleaner code, we can use destructuring assignment:
const arr = [
{"time":"18:00:00"},
{"time":"10:00:00"},
{"time":"16:30:00"}
];
const reduceArray = (arr = []) => {
return arr.map(({time}) => {
const [hours, minutes] = time.split(':');
return [Number(hours), Number(minutes)];
});
};
console.log(reduceArray(arr));
[ [ 18, 0 ], [ 10, 0 ], [ 16, 30 ] ]
Conclusion
The map() method is perfect for transforming array elements. This approach efficiently converts time objects into numeric hour-minute pairs using string manipulation and array methods.
