0

I have an array that stores me some values like this:

array[0] = "string", "string"
array[1] = "string", "string"
array[2] = "string", "string"
array[3] = "string"

As you see sometimes i have 2 values on same index, but sometimes i don't. Then i need to push those values to another array, one value by one.

I can't use this:

for(var i= 0; i< 4 ; i++){
    newarray.push(array[i][0]);
    newarray.push(array[i][1]);
}

Otherwise i would push blank values (i guess).

How can i check if i have 2 values on that index or one value, so i can use a different circle?

Thank you!

3 Answers 3

1

Your code is probably not working as expected, when you do this:

array[0] = "a", "b", "c"

It will assign only "a" to array[0] and return "c". To assign another array with these values, you should use something like this:

array[0] = ["a", "b", "c"]

To maintain the structure consistence, if I had only one element in the array I would use an array structure too.

array[1] = ["a"]

Using this, you could iterate over your array and then over your nested arrays to get their values.

for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        newarray.push(array[i][j]);
    }
}

Fiddle: http://jsfiddle.net/nDhP5/

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

4 Comments

Yes i had array[0] = ["a", "b", "c"] forgot to type "[..]". But that way i wont get blank values when i display them on some label?
Didn't understand your question about the label. Can you provide some more context?
My project is about creating 2 teams :) I have another 2 arrays so i push those values from the other array. Then I want to display the values between those 2 teams.
I forgot to say, i want to mantain the double values together on the same team.
0

How can i check if i have 2 values on that index or one value, so i can use a different cicle?

Assuming you mean you are storing multiple values in an array at one key, you can check the length of the array containing those values. This way you can see if you have 1 or 2 or more values.

if (array[i].length == 1) { // you have 1 value }

if (array[i].length == 2) { // you have 2 values }

Comments

0

you can do like this

var Rdata = []; 
var temp_ray = ["v1","v2","v3"];
Rdata.push(temp_ray);
var Rlen = Rdata.length;
console.log('Rdata length '+Rlen);     // 1

JsFiddle :: Jsbin demo

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.