Question

I have a JavaScript array which looks like this:

var arr = ["[Dim1].[Mem1].&[1]",
           "[Dim2].[Mem1].&[2]",
           "[Dim1].[Mem1].&[5]",
           "[Dim2].[Mem1].&[77]",
           "[Dim3].[Mem1].&[1]"
          ]

I want output in this format:

{
    [Dim1].[Mem1].&[1], [Dim1].[Mem1].&[5]
},
{
     [Dim2].[Mem1].&[2], [Dim2].[Mem1].&[77]
},
{
     [Dim3].[Mem1].&[1]"]
}

The idea is to split each value based on '.&' and then group by the result[0].

I am able to do this by:

  1. Loop over all the items in array & then split them with .&
  2. Create another list based on [dim].[mem] combination. In our case the list will have [Dim3].[Mem1], [Dim1].[Mem1], [Dim2].[Mem1].
  3. Now have two loop - One for every item in unique list and one for every item in original list & check if the item is original list contains the current item in unique list & then form the string.

How can I achieve this using "lodash" or any other JS based library which will reduce the code and make the method compact?

Was it helpful?

Solution

Quite literally, actually:

_.chain(arr)
.invoke("split", ".&")
.groupBy(0)
.map(function(els) {
    return "{\n\t"+ _.invoke(els, "join", ".&").join(", ") + "\n}";
})
.value().join(",\n");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top