Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

81
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda