Reduce array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ] ]
raja
Published on 20-Nov-2020 18:22:36
Advertisements