Search code examples
javascriptarrayslodash

Lodash function to modify each element in array of strings


I have the following array:

let array = [ "c0709f80b718", "c47b86124fde" ];

What is the fastest lodash function to be able to add the ":" in eacch element of the array to convert to a mac address format.

Expected output should be:

let array = [ "c0:70:9f:80:b7:18", "c4:7b:86:12:4f:de" ];

Solution

  • Use Array.map() to iterate the array, and a RegExp with String.match() to split each string, and then join it with :.

    const array = [ "c0709f80b718", "c47b86124fde" ];
    
    const result = array.map(str => str.match(/.{2}/g).join(':'))
    
    console.log(result)

    As @Akrion suggested, with lodash you can use _.words with the same RegExp pattern to split the string:

    const array = [ "c0709f80b718", "c47b86124fde" ]
    
    const result = _.map(array, str => _.words(str, /.{2}/g).join(':'))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>