1

I have pre-existing two arrays on the webpage that I need to customize, one with strings and other with corresponding id's. I need to replaces the strings in array1 based on the information I get using array2. I have problem looping through array1 as it only gives me length = 1 in all cases.Why so? Is there any better way to accomplish this task? I will appreciate any help I can get. Thanks

var arr1= [[ "Khyle", "Marlen", "Jose"]];
var arr2= [[ "51", "69","22"]];
//replace extra square brackets
 var str =  arr2.replace((/[\[[']+/g,'[');   
 str= str.replace((/[\]]']+/g,']');      
 var length = str.length, element = null; 
for (var i = 0; i < length; i++) {
            element = str[i];
        // Ajax call to get the info and load in arr1[i]
             arr1[i] = ajax-str
        }
1
  • 2
    Correct me if I'm wrong, but isn't replace a String method? You're calling it on an array Commented Dec 8, 2015 at 18:56

3 Answers 3

2

You have got an array inside an array. This is why the array length is 1. It should be:

var arr1= [ "Khyle", "Marlen", "Jose"];

var arr2= [ "51", "69","22"];

or you could write arr1 = arr1.pop() to get the array outside of array.

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

Comments

2

This is the reason why:

var arr1= [[ "Khyle", "Marlen", "Jose"]];

That dimensions out to the equivalent of arr1[0][strings], or 2 dimensions.

so, element 0 will always have a length of 1.

Comments

2

The reason you're getting an array length of 1 is because you're using double brackets, and you only need one pair of brackets to define an array in Javascript.

Because of that, you're actually creating an array that holds a single element: another array which holds the strings "Khyle", "Marlen" and "Jose".

Comments

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.