1

I have problem with draw adjacency matrix from javascript object.

My object:

var result = {
    "D5":  ["D#5", "A#4", "D#5", "A#4"],
    "D#5": ["D5", "D5"],
    "A#4": ["G4", "D5", "F5"],
    "G4":  ["A#4"],
    "F5":  ["A#4"]
}

I want to get output:

        D#5 A#4 D5 G4 F5

D5      2   2   0   0  0

D#5     0   0   2   0  0

A#4     0   0   1   1  1

G4      0   1   0   0  0

F5      0   1   0   0  0 

How to count values in key?

I make draft:

for (var key in result){
         console.log('Key: ' + key + ' values: ' + result[key])


            for(var val in result[key]){
                // console.log(result[key][val]);

                var counter = 0;
                for(var v in result[key]){
                    if (result[key][v] === result[key][val]){
                        counter++;
                    }
                }
                console.log('Value ' + result[key][val] + 'count' + counter)
            }
        }
6
  • what exactly is the problem? What is the output now? Commented Apr 5, 2018 at 12:39
  • @Jeff my code couting elements but not for 0 (non exist elements) Commented Apr 5, 2018 at 12:41
  • Do you expect a tabular output? or just object count? Commented Apr 5, 2018 at 12:43
  • Just object count like key: [0,0,1,2,1], key2: [2,1,4,2,1] Commented Apr 5, 2018 at 12:46
  • it's then only a matter of how you display it. Commented Apr 5, 2018 at 12:47

4 Answers 4

1

You can use reduce

let result = {"D5":["D#5","A#4","D#5","A#4"],"D#5":["D5","D5"],"A#4":["G4","D5","F5"],"G4":["A#4"],"F5":["A#4"]};
let order = Object.keys(result).reduce((c,v)=>Object.assign(c,{[v]:0}),{});		//Make Dynamic Order

let count = Object.keys(result).reduce((c, v) => {
  return Object.assign(c, {[v]: result[v].reduce((p, o)=>{
      p[o] += 1;
      return p;
    }, Object.assign({}, order))});
}, {});

console.log(count);

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, but how we can add 0 for non existant path?
Is this going to be the order D#5 A#4 D5 G4 F5? Or is it doing to be dynamic?
No, D5 D#5 A#4 G4 F5 order like keys order in object. Dynamic like keys.
Happy to help @lukassz :)
btw my point is to make animation like this teropa.info/generative-music-slides/#/markov_chains but I have to go to a bigger level in js ;)
0

This works, using forEach for result[key]

var result = {
	"D5":["D#5","A#4","D#5","A#4"],
  "D#5":["D5","D5"],
  "A#4":["G4","D5","F5"],
  "G4":["A#4"],"F5":["A#4"]
 };
var final = {};
for (var x in result){
	final[x] = {};
  for(var y in result){
    final[x][y]=0;
  }
	result[x].forEach(function(z){
    final[x][z]++;
  });
}
console.log(final);

1 Comment

@lukassz is it okay?
0

You could use one Set to get all the unique sub-array elements, and then reduce method to get object with count of each element in those sub-array. Then you could add that data to one table.

const data = {"D5":["D#5","A#4","D#5","A#4"],
"D#5":["D5","D5"],"A#4":["G4","D5","F5"],"G4":["A#4"],"F5":["A#4"]}
const table = document.querySelector('table tbody');

const keys = new Set();
const output = Object.keys(data).reduce((r, key) => {
  data[key].forEach(e => {
    keys.add(e);
    if (!r[key]) r[key] = {}
    r[key][e] = (r[key][e] || 0) + 1;
  })
  return r;
}, {})


table.innerHTML += '<tr><td></td>' + Array.from(keys).map(e => `<td>${e}</td>`).join('') +'<tr>';
Object.keys(output).forEach(key => {
  let data = `<td>${key}</td>`;
  data += Array.from(keys, e => '<td>' + (output[key][e] ? output[key][e] : 0) + '</td>').join('')
  table.innerHTML += `<tr>${data}</tr>`;
})
<table><tbody></tbody></table>

Comments

0

Just ES5

var result = {"D5":["D#5","A#4","D#5","A#4"],
"D#5":["D5","D5"],"A#4":["G4","D5","F5"],"G4":["A#4"],"F5":["A#4"]}

/***************************************************************************/
/*********************** THIS IS WHAT YOU ASKED ****************************/
/***************************************************************************/

function myCustomFunction(array){
  // VAR USED TO STORE THE UNIQUE KEYS
  var inner_keys = [];

  // LOOP TO GET THE UNIQUE KEYS
  Object.keys(array).map(function(a){inner_keys = inner_keys.concat(array[a])})
  inner_keys = inner_keys.filter(function(a,b,c){return c.indexOf(a) === b});

  //  VAR USED TO STORE THE FINAL RESULT
  var result = {};

  // LOOP TO GET THE AMOUNT OF REPETITION FOR EACH KEY IN THE ORIGINAL ARRAY
  Object.keys(array).map(function(a){
    result[a] = inner_keys.map(function(b){return array[a].filter(function(c){return c==b}).length})
  })
  
  // RETURNS THE UNIQUE KEYS AND THE RESULT
  return {orderOfKeys: inner_keys, result: result};
}

/**************************************************************************/
/**************************************************************************/
/**************************************************************************/



/**************************************************************************/
/******************** THIS IS JUST TO PRINT IT INTO A TABLE ***************/
/**************************************************************************/

function fillTable(array){
  var table_header = array.orderOfKeys;  
  var table_body = array.result;
  var thead = document.getElementById("thead");  
  var tbody = document.getElementById("tbody");
  
  createElement('TR', thead)    

  for(var i = 0; i < table_header.length; i++){
    if(i == 0){
      createElement('TH', thead.children[0], '')
    }
    createElement('TH', thead.children[0], table_header[i])
  } 
  
  for(var k in table_body){
    var row = createElement('TR', tbody);
    for(var i = 0; i < table_body[k].length; i++){
      if(i == 0){
        createElement('TD', row, k)
      }
      createElement('TD', row, table_body[k][i])
    }
  }  
  
}

function createElement(el, parent, value){
  var element = document.createElement(el);
  if(value != undefined){
    var element_text = document.createTextNode(value);
    element.appendChild(element_text);
  }
  parent.appendChild(element);
  return element;
}

/**************************************************************************/
/**************************************************************************/
/**************************************************************************/


fillTable(myCustomFunction(result))
<table>
  <thead id="thead">
  </thead>
  <tbody id="tbody">
  </tbody>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.