0

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?

3
  • 1
    Something is very wrong here. Seems like an X/Y problem. Your data should never be this hard to reason about. I can't really wrap my head around why you're asking. Commented Mar 13, 2015 at 2:15
  • You have one array which objects are other arrays? And You want to compare those arrays among themselves, but could you explain with more details how? Commented Mar 13, 2015 at 2:17
  • You mean I need to make them as associative array? Commented Mar 13, 2015 at 2:17

1 Answer 1

1

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 } }

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

5 Comments

Thank you very much meagar!. I have a question what if I changed the data = {}; to data = [];. What would be happen to the output? Thanks
You shouldn't. There is no reason to use an array for this.
can you explain to me but why? I tried it but its shows me undefined data. Is javascript and angularjs can support arrays? Thanks again
... Yes, JavaScript and Angular support arrays, but I don't know why you want to use one. Doing so will create sparse arrays, and the holes will be filled with undefined.
Ah okay now I understand it. Thank you meagar for your help.

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.