How do I go about mapping an adjacency list for a directed, weighted graph from an array of arrays?
I'm actually trying to do this in Google Apps Script, so I'm pulling the values from a Google Sheet, which is returned like this:
[[a, b, 2], [b, a, 1, g, 7], [c, d, 4], [d, c, 3, g, 7], [e, a, 1, c, 3], [f, a, 1, c, 3], [g, h, 8]]
And I need the output to be like this:
graph = {
a: { b: 2 },
b: { a: 1, g: 7 },
c: { d: 4 },
d: { c: 3, g: 7 },
e: { a: 1, c: 3 },
f: { a: 1, c: 3 },
g: { h: 8 },
};
Each array within the array of arrays has an indeterminate length, depending on how many key value pairs are assigned to the key (first element). The array of arrays also has an indeterminate number of arrays within it as new arrays are added and removed all the time.
I've tried map, slice, splice, flat and spread, but I can't seem to figure out how to get the desired output.
Thanks in advance!
a simple way:
Note that we're not validating anything, if you have an array with even elements, this will not work ๐
userArray = [
["a","b",2],
["b","a",1,"g",7],
["c","d",4],
["d","c",3,"g",7],
["e","a",1,"c",3],
["f","a",1,"c",3],
["g","h",8]
];
// array to object
arrToObj = (arr) => {
var r = {};
// note that we start from array position 1 (as 0 was the key)
for(i = 1; i < arr.length; i = i + 2) {
r[arr[i]] = arr[i+1]; // assign 1st as key, 2nd as value
};
return r;
};
r = {}; // result
userArray.forEach(x => {
// assign 1st element as key
// use helper function to transform the array to object
r[x[0]] = arrToObj(x);
});
console.log(r);