Pregunta

Look at the below code or this fiddle

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

var res = _.chain(arr)
    .invoke("split", ".&")
    .groupBy(0)
    .map(function (els) {
        return "{ " + _.invoke(els, "join", ".&").join(", ") + " }";
    })
    .value();

console.log(res);

this produces following output:

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

The above code is using lodash library. It looks at the array and splits the values by '.&' and then groups the data by the resultant array's zero'th index.

This code is working fine and its doing whats its suppose to do.

Now consider a scenario where the input array does not have '.&' in it. In that case I want to split the input by '.' and then group the values. Is it possible to achieve the desired result by modifying code above? Or is it possible to do conditional split based on the input value?

var arrTwo = ["[Dim1].[Mem1].&[1]",
              "[Dim2].[Mem1].&[2]",
              "[Dim1].[Mem1].&[5]",
              "[Dim2].[Mem1].&[77]",
              "[Measures].[M11]",
              "[Dim2].[Mem1].[All].Child",
              "[Dim3].[Mem1].&[1]"],
              "[Measures].[M1]",
              "[Measures].[M2]";

Expected output:

[

"{ [Dim1].[Mem1].&[1], [Dim1].[Mem1].&[5] }" , 
"{ [Dim2].[Mem1].&[2], [Dim2].[Mem1].&[77] }", 
"{ [Dim2].[Mem1].[All].Child }", 
"{ [Dim3].[Mem1].&[1] }",
"{[Measures].[M11], [Measures].[M1], [Measures].[M2]}"
]
¿Fue útil?

Solución

I'd suggest a regular expression in the groupBy callback instead of split:

var res = _.chain(arrTwo)
    .groupBy(function(x) {
        return x.match(/.+?\.&|[^.]+\./)[0]
    })
    .map(function (x) {
        return "{ " + x.join(", ") + " }";
    })
    .value();

This seems to produce the desired result: http://jsfiddle.net/aAy6L/2/

That regular expression first tries to match everything up to, and including, .&. If it fails (i.e. there's no .& in the string) it backtracks and tries to match "some non-dots and a dot". The found match is used as a groupBy key.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top