Formatting javascript array list into specific format using lodah\handlebar template or any other JS library

StackOverflow https://stackoverflow.com/questions/22961530

Pregunta

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"]

What I want: I want a string in this format

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

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.

Is there anyway to achieve this with the help of a template or handlebar template or any other JavaScript library?

¿Fue útil?

Solución

You can use _.groupBy and Regular Expressions, to group the elements

var regExp = /\[(.*?)\]/g;
console.log(_.groupBy(arr, function(currentItem) {
    var match, result = "";
    while ((match = regExp.exec(currentItem)) !== null) {
        result += match[1];
    }
    return result;
}));

Output

{ Dim1Mem1: [ '[Dim1].[Mem1].&1', '[Dim1].[Mem1].&5' ],
  Dim2Mem1: [ '[Dim2].[Mem1].&2', '[Dim2].[Mem1].&77' ],
  Dim3Mem1: [ '[Dim3].[Mem1].&1' ] }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top