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:

  1. obj['time'] - extracts the time string
  2. .split(':') - splits "18:00:00" into ["18", "00", "00"]
  3. .slice(0, 2) - takes only first two elements ["18", "00"]
  4. .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.

Updated on: 2026-03-15T23:19:00+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements