Here is my array:
const main = [
[['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369']],
];
and here is my function:
const convertor = (x) => {
const splitted = x.split(':');
console.log(splitted);
const converted = splitted[0] * 60 + splitted[1] * 60 + splitted[2];
return converted;
};
I want to map this function on each nested array
I tried this but I got an error:
const resu = main.map((x) => {
x.map((y) => {
convertor(y);
});
});
x.split is not a function
Issues
maps()return is required if you use {} in the arrow functionconst main = [
[['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369']],
];
const convertor = (x) => {
const splitted = x.split(':');
const converted = splitted[0] * 60 + splitted[1] * 60 + splitted[2];
return converted;
};
const resu = main.map((x) => {
return x.map((y) => {
return y.map((z) => {
return convertor(z);
});
});
});
console.log(resu);
Shorter version
main.map(x => x.map(y => y.map(convertor)));
const main = [
[
['02:20:21,369'],
['02:20:21,369'],
['02:20:21,369'],
['02:20:21,369']
],
[
['02:20:21,369'],
['02:20:21,369']
],
[
['02:20:21,369'],
['02:20:21,369'],
['02:20:21,369']
],
[
['02:20:21,369']
],
];
const convertor = (x) => {
const splitted = x.split(':');
//console.log(splitted);
const converted = splitted[0] * 60 + splitted[1] * 60 + splitted[2];
return converted;
};
const mappedMain = main.map(i => {
return i.map(j => {
return convertor(...j)
})
})
//Or
//const mappedMain = main.map(i => i.map(j => convertor(...j)))
console.log(mappedMain);
You made some mistakes:
Expression (x) => { /* a few lines of code */ } requires the use of the return keyword to return the result, while (x) => /* single line of code */ doesn't.
Your array main is three-dimensional array, not two-dimensional.
Try this:
const resu = main.map((x) => {
return x.map((y) => {
return y.map(convertor);
});
});
Or easier:
const resu = main.map(
(x) => x.map(
(y) => y.map(convertor)
)
);
const main = [
[['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369'], ['02:20:21,369'], ['02:20:21,369']],
[['02:20:21,369']],
];
const convertor = (x) => {
const splitted = x.split(':');
const converted = splitted[0] * 60 + splitted[1] * 60 + splitted[2];
return converted;
};
const resu = main.map(
(x) => x.map(
(y) => y.map(convertor)
)
);
console.log(resu);