Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
How to Map a Directed Weighted Graph from an Array of Arrays

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!

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

a simple way:

  • loop through the array, and make the first value the key
  • pick up the rest of the values and loop through them 2 by 2

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);

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!