Search code examples
javascriptfunctional-programminglodash

Functional way to build array of arrays in JavaScript


I have a string which is the path to a value in a nested JavaScript object e.g.:

users.userA.credentials.name

I would like to split this string into its elements and then create an array with all "sub-paths", like so:

["users", "users.userA", "users.userA.credentials"]

Currently I'm solving this the following way:

const path = "users.userA.credentials.name"
const currentPath = []
const paths = []

for (const item of path.split('.')) {
  currentPath.push(item)
  paths.push([...currentPath])
}

It works fine, but I was wondering, if there is a more functional way (using map(), filter(), reduce() or maybe some lodash/ramda functions to achieve the same result.


Solution

  • You can use Array.split() and Array.map() to do it in a more functional way:

    const path = "users.userA.credentials.name"
    const paths = path.split('.')
      .map((_, i, arr) => arr.slice(0, i + 1).join('.'));
    
    console.log(paths);