Search code examples
javascriptpodio

Change values in an array (javascript)


I have a field in our CRM system with order numbers listed in the following way:

544,543,53

Note : This is an example, the amount and size of these numbers can vary.

How do I change these numbers to:

HPO0000000544,HPO0000000543,HPO0000000044

Please note that the amount of 0s in the HPO codes depends on the size of the order number. HPO should always be followed by 10 numbers (0s + the order number).

I've tried to look for the solution, but haven't been able to find anything. Unfortunately I don't know enough about javascript to write the code myself.


Solution

  • You need to map the array (map each value of the array to another one) by using padStart:

    function toHPO(number) {
        return `HPO${number.toString().padStart(10, '0')}`;
    }
    const arr = [544,543,53];
    console.log(arr.map(toHPO));

    Note that you might need to add a polyfill depending on which browsers you target.