Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

83
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda