Reputation: 583
I have the following array:
[["1", "2", "Anna"], ["1", "2", "Jodie"], ["1", "2", "susan"]]
My question is how can I output them as shown below?
I want to get all 1
as there parent index:
(
[1] =>Array
(
[2] => 3
)
)
The number 1
means the O
index of array of arrays.
The 2
is the 1
index and 3
means how many students which 1
index is equal to two. In above array there are 3 students.
Any ideas?
Upvotes: 0
Views: 269
Reputation: 239521
My understanding is that, given a record in the form [a, b, c]
, You want to produce an array summing the number of times you can reach a value by traversing through a
to b
.
Given [ [a,b,x], [a,b,y], [a,b,z] ]
your output would be{a: {b: 3}}
.
Given [ [a,b,x], [a,b,y], [c,d,x], [c,d,y], [e,f,z]]
, your output would be
{
a: {
b: 2
},
c: {
d: 2
},
e: {
f: 1
}
}
This is relatively simple:
records = [
["1", "2", "Anna"],
["1", "2", "Jodie"],
["1", "2", "susan"]
]
data = {}; // this will hold your final structure
records.forEach(function (r) {
var first = r[0], second = r[1];
// create the first dimension unless it exists
data[first] || (data[first] = {});
// create the second dimension unless it exists
data[first][second] || (data[first][second] = 0);
data[first][second]++;
});
console.log(data); // { "1": { "2": 3 } }
Upvotes: 1