javascript - LoDash - How to push one collections values into another via common key -
i have 2 collections.
var = [ {unique_id: "001", state: "co"}, {unique_id: "001", state: "tx"}, {unique_id: "001", state: "cc"}, {unique_id: "002", state: "cc"}, {unique_id: "002", state: "ny"} ]
and
var b = [ {unique_id: "001", states:[]}, {unique_id: "002", states:[]} ]
and want get:
var b = [ {unique_id: "001", states:["co","tx","cc"]}, {unique_id: "002", states:["cc","ny"]} ]
i should mention "b" array has stay in same order it's in , of unique_id's don't have value.
i've been trying use lodash https://lodash.com/ - if can solve lodash awesome!
the time complexity of solution suboptimal ( o(n^2) ), might think of ways match pushing values "b":
_.foreach(a, function(element1){ _.foreach(b, function(element2){ if (element2.unique_id === element1.unique_id) { element2.states.push(element1.state); } }); });
perhaps better solution might index objects in b unique id using lodash's _.indexby method. example can index objects in b follows:
var c = _.indexby(b, 'unique_id')
which result in:
{001:{unique_id: "001", states:[]}, 002: {unique_id: "002", states:[]}}
since objects in our c array pointing same objects in memory in our b array, can directly mutate our objects in c , b reference updated objects in memory. so:
_.foreach(a, function(element1){ if (element1.unique_id in c) { c[element1.unique_id].states.push(element1.state); } })
now if take @ our b array, we'll see value is:
var b = [ {unique_id: "001", states:["co","tx","cc"]}, {unique_id: "002", states:["cc","ny"]} ]
the time complexity of solution should close o(n), better using nested _.foreach approach. code snippet:
var = [ {unique_id: "001", state: "co"}, {unique_id: "001", state: "tx"}, {unique_id: "001", state: "cc"}, {unique_id: "002", state: "cc"}, {unique_id: "002", state: "ny"} ]; var b = [ {unique_id: "001", states:[]}, {unique_id: "002", states:[]} ]; var c = _.indexby(b, 'unique_id'); _.foreach(a, function(element1){ if (element1.unique_id in c) { c[element1.unique_id].states.push(element1.state); } }); document.writeln(json.stringify(b))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.js"></script>
Comments
Post a Comment