0

I'm writing a script to initalize 2d array in javascript by reading txt file. Here are some portions of my code

var neighbor = {};
var temp = new Array();
neighbor[nodemap[ temparray[0]]] = temp; //nodemap[ temparray[0]] is an integer
neighbor[nodemap[temparray[0]]]. push(nodemap[temparray[1]]);
neighbor[nodemap[temparray[0]]]. push(nodemap[temparray[2]]);
.... // continue to add value

Then I want to access and sort the array, like this

for (var i = 0; i < n_count; i++);
{
  for (var k = 0; k < neighbor[i].length; k++);
    neighbor[k].sort(function(a,b){return a - b})
}

However, I got the error that neighbor[i] is unidentified. Could you please show me how to fix that?

3
  • 4
    Well ... what is i? Commented Apr 5, 2013 at 14:29
  • i guess u should have used 'k' instead of i ? is 'i' in scope ? Commented Apr 5, 2013 at 14:32
  • Sorry, it's k... I made mistakes, i editted the post already Commented Apr 5, 2013 at 14:34

1 Answer 1

1

Your neighbor "array" is actually an object literal. So the way you should loop over neighbor is:

for (var key in neighbor) {
    var cur = neighbor[key];
    cur.sort(function (a,b) {
        return a - b;
    });
}
Sign up to request clarification or add additional context in comments.

7 Comments

If neighbor[i] is undefined then neighbor[i][k] won't be accessible either. I also think neighbor[i] is supposed to be an array that they want to sort.
@AnthonyGrist Yeah I'm starting to realize a few things. I've been editing to explain more. Thanks for pointing it out
@JoshVo I know, I've been editing my answer. I just finished. Does that help? Can you provide a jsFiddle with your actual filling of neighbor?
thanks Ian. It works. However, I still need to write back right? (i.e neighbor[key] = cur;) Is there any method I could sort directly? I am working with a very large data...
@JoshVo No, you don't need to write back. When you have var cur = neighbor[key];, cur will be a reference to the specific array in neighbor. So it gets modified in place. Here's an example - jsfiddle.net/DwaAa . And I can't think of any other way to sort these
|

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.