I am using a kind of dict in javascript and want to add an element to a list which is part of a kind of dictionary.
Here is the code snippet:
lines = [
[1,2],
[2,4],
[2,3],
[3,5]
];
nodes = [1,2,3,5,4];
function get_adjdict(nodes, lines) {
// create an empty something
adjacent = [];
// loop over all elements on the array 'nodes'. The variable 'node' is supposed to take the various values of the elements in 'nodes'. So in this example this will be the values 1,2,3,5,4.
for (var node in nodes) {
// Add a key-value pair to the object/array/whatever named 'adjacent'. key is the value of 'node, the value is an empty array.
adjacent.push({node:[]});
// loop over all elements on the array 'lines'. The variable 'line' is supposed to take the various values of the elements in 'lines'. So in this example this will be the values [1,2], then [2,4] and so on
for (var line in lines) {
// checks if the value of 'node' is present in the array 'line'
if (line.includes(node)) {
// If the first element of the array 'line' has the same value as 'node'...
if (line[0] == node) {
// ... add the second element of 'line' to 'adjacent[node]'
adjacent[node].push(line[1]) //ERROR
} else {
// ... add the first element of 'line' to 'adjacent[node]'
adjacent[node].push(line[0])
}
}
}
}
return adjacent
}
The error is "TypeError: adjacent[node].push is not a function". How to do it then?
Expected data-structure:
adjdict = {
1: [2],
2: [1,4,3],
3: [2,5],
4: [2],
5: [3]
}
adjacent[node].node.push, but I htink that is also wrong since indexes start at zero.