How to get Javascript array length?

What is the best way to get output from a 2 layer loop for 2D array in Javascript?

  • Here is my code: var myArray = {}; myArray["abc"] = new Array(); myArray["def"] = new Array(); myArray["abc"][0] = "John"; myArray["abc"][1] = "Mary"; myArray["abc"][2] = "Jack"; var letter = ""; var id = ""; for (var i_letter in myArray) { for (var j_id = 0; j_id < myArray[i_letter].length; j_id++) { if (myArray[i_letter][j_id]=== "Mary") { letter = i_letter; // error ? id = j_id; // error? } } } document.write( letter + “ , ” + id); // why error? Suppose to be “abc , 1” What is the best way to get output, namely i_letter and j_id, from outside the loop?  By the way, if myArray contains huge data, is there anyway to write codes more efficiently?

  • Answer:

    First of all myArray as you defined it is not a JavaScript array but a JavaScript object and then do not provide JavaScript Array methods The Array like notation in is used in JS to set dynamically the name of the object property you want to get In this code myArray = {}; // object literal notationmyArray["abc"] = new Array(); // similar to myArray.abc = new Array(); This notation would have let you define the "abc" property name in a variable var indexName = "abc";myArray[indexName] = new Array(); And the property name could even be the result of an expression myArray[indexName + i] = new Array(); In JS {} represent an object and [] represent an array Note that it is a better practice to use the literal array notation than new Array() myArray.abc = [] // similar to myArray.abc = new Array(); A potentially better version of your code, keeping myArray as an object (I'll call it "data"), could be var data = { // was "myArray" abc: ["John", "Mary", "Jack"], // new Array() with items 0, 1, and 2 def: [] // new Array()};var result;var arrayNames = Object.keys(data); // get data property names in an arrayarrayNames.forEach(function (name) { // parse the propNames array items data[name].some(function (value, index) { // parse array value until item found if (value === "Mary") { result = [name, index]; return true; } return false; });});console.log(result); About the error in your code it comes from the fact that in this line: document.write( letter + “ , ” + id); The used double quote (") character is not the valid JS (ASCII) double quote character. This version would work better: document.write( letter + " , " + id); [EDIT] I realize I didn't talked about the context of huge array So, if you have a huge array such code may be blocking the UI as the Array forEach is nor asynchronous. This lib provides a way to do Async forEach on arrays: https://github.com/cowboy/javascript-sync-async-foreach. It would nor result in better "performances but at least would make the interface still responsible. You could even show an advancement status via a progress bar if needed. If you're arrays are so big, you may consider to index your values, reproducing btree or cluster indexes is not that hard in JS. Note that you might consider to use IndexedDB (with a polyfil for Safari) or also split your arrays in different shared workers trough which you could implement a map/reduce mechanism

Alexandre Morgaut at Quora Visit the source

Was this solution helpful to you?

Other answers

First of all, I think this particular question should be asked on http://stackoverflow.com/ (if it isn't already answered there) Secondly, your code works. There must be something wrong that you're doing. Regarding huge data, it really depends on how you model your data and what you use it for. Some small tips: don't use strings as keys, but http://en.wikipedia.org/wiki/Hash_functionthem use indexes on keys if they are in huge numbers even if you're working in JS, take a look at this http://en.wikipedia.org/wiki/Category:String_matching_algorithms and see if it's ok with you (myArray[i_letter][j_id]=== "Mary") when looping, if you need just one value, break the loop when you found it. As I said before, your question best resides on SO. UPDATE: Replace `document.write()` with `console.log()` (http://stackoverflow.com/questions/14086675/which-browsers-support-console-log)

Radu Cruceru

1. Ask these type of adhoc questions on Stackoverflow. Ask more generalized questions on Quora. 2. What are you trying to achieve here ? I'll update my answer once you clarify this. If you want two different collections in a single object, and you want to perform fast searches, implement a trie in JavaScript. If the number of elements in a collection is not so high then you're not performing a CPU intense operation. Here, you could just use hash like this. myArray["abc"]["John"] = id1myArray["abc"]["Mary"] = id2 But searching is faster in a trie. Here is an analysis by John Resig. http://ejohn.org/blog/javascript-trie-performance-analysis/ for(var i in myArray) if(myArray.hasOwnProperty(i)) if( myArray[i].hasOwnProperty("Mary") ) { letter = i; id = myArray[i]["Mary"] break; }

Boopathi Rajaa

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.