Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function on a nested array in js

Here is my Function which turns timestamps to seconds,

   const convertor = (x) => {
      const result = x.split(':');
      const final =
        parseInt(result[0] * 60) +
        parseInt(result[1] * 60) +
        parseInt(result[2]) -
        1.2;
      return final;
    };

input = 00:01:02.330
result: 62.330

How can I implement it on a nested array like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array = [ [ 00:01:02.330],[00:01:04.550],[01:11:02.330] ], [ [00:01:02.330],[00:01:02.330] ] , [ [00:01:02.330],[00:01:02.330],[00:01:02.330] ] ]

I want to preserve its nested structure so the result should be:

[ [ 22.3],[28.5],[903.50] ], [ [1252.3],[62.2] ] , [ [654.25],[965.25],[1254.32] ] ]

>Solution :

You can write a wrapper that accepts a function and an array, and maps over the array– if the item is an array, it recurses; otherwise, it passes the item into the passed function– this allows you to process nested arrays of any arbitrary depth and retain the desired structure:

const convertor = (x) => {
  const result = x.split(':');
  const final =
    parseInt(result[0] * 60) +
    parseInt(result[1] * 60) +
    parseInt(result[2]) -
    1.2;
  return final;
};

const recursiveNestedMapper = (fn, arr) => {
  const output = arr.map((item) => {
    if (Array.isArray(item)) {
      return recursiveNestedMapper(fn, item);
    } else {
      return fn(item);
    }
  });

  return output;
}

const inputArray = [
  [
    ['00:01:02.330'],
    ['00:01:04.550'],
    ['01:11:02.330']
  ],
  [
    ['00:01:02.330'],
    ['00:01:02.330']
  ],
  [
    ['00:01:02.330'],
    ['00:01:02.330'],
    ['00:01:02.330']
  ]
];

const outArray = recursiveNestedMapper(convertor, inputArray);

console.log(outArray);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading