Forum Discussion
Anonymous
3 years agoNot applicable
Replace one value by multiple values
Hi everyone! I have the following table (simplification): Product Ingredients weight % A a 0.5 A b 0.5 a m 0.4 a n 0.6 m x 0.9 m z 0.1 I need to brea...
wdx223_Daniel
3 years agoCommunity Champion
= let tbl=Table.Buffer(Source),fx=(t)=>let a=tbl{[Ingredients=t{0}]}? in if a=null then t else Fx({a[Product],t{1}? ??a[Ingredients],Text.Combine({a[#"weight %"],t{2}?},"*")}) in #table(Table.ColumnNames(Source),List.Transform(List.RemoveItems(Source[Ingredients],Source[Product]),each fx({_})))
AlexisOlson
3 years agoSuper User
Classic wdx223_Daniel! Brilliant solution but takes effort to understand.
I think I've deciphered it and this is my annotated translation of it that may help future readers follow along too:
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUUoEYgM9U6VYHQg/CYkPkssF803g/Dww3wzMB8lVgPmWcH4VmG+oFBsLAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Product = _t, Ingredients = _t, Weight = _t]),
tbl = Table.Buffer(Source),
/*Define recursive lookup function.*/
fx =
(L as list) => // {lookup, (optional) ingredient, (optional) weight}
let
lookup = L{0}, // 1st item in list
ingredient = L{1}?, // 2nd item in list or else null
weight = L{2}?, // 3rd item in list or else null
/*Lookup ingredient row in tbl or return null*/
row = tbl{[Ingredients = lookup]}?,
recursive_step =
if row = null
then L // End recursion
else // Recursively call fx on new values
@fx(
{
row[Product], // new lookup
ingredient ?? row[Ingredients], // new ingredient
/*List.Product({row[Weight], weight}), // multiply weights*/
Text.Combine({row[Weight], weight}, "*") // concatenate weights
}
)
in
recursive_step,
/*Ingredients not appearing in the [Product] column*/
leaf_ingredients = List.RemoveItems(tbl[Ingredients], tbl[Product]),
/*Apply recursive lookup function to each leaf ingredient.
Each ingredient becomes {Product, ingredient, weights}.*/
tbl_rows = List.Transform(leaf_ingredients, each fx({_})),
col_names = Table.ColumnNames(tbl),
/*Construct table from column names and list of rows*/
result = #table(col_names, tbl_rows)
in
result