简体   繁体   中英

Reversing Many to Many Relationship array

var x = {one:[1,2,3],two:[3],three:[2]}
var y = {1:['one'], 2:['three', 'one'], 3:['one', 'two']}

How can I turn var x to var y? Basically, x is of the form set->user_arrays , set->user_arrays , when I want to 'reverse' them and get user->set_arrays . Preferably the fastest solution, and functional (map etc.)

var x = {one:[1,2,3],two:[3],three:[2]}
var y = {};

for (var k in x) {
  for (var i = 0; i < x[k].length; i++) {
    y[x[k][i]] = y[x[k][i]] || [];
    y[x[k][i]].push(k);
  }
}

THE WORKING DEMO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM