2

Ok, so I have this simple code :

for(var i=0; i<lines.length; i++) {
    elements += myFunction(lines[i]);
}

Where elements is an empty array at the start and myFunction() is just a function that returns an array of strings.

The problem is that if myFunction() returns an array with a single string, the += is interpreted as a string concat in place of an array concat. At the end of the loop the result is just a long string and not an array.

I tried push()ing the values in place of concatenation, but this just gives me a two dimensional matrix with single item arrays.

How can I solve this typecasting problem ? Thank you in advance !

2
  • Plz give some code , what have you tried and some example would be handful to help you. Commented Dec 18, 2012 at 6:46
  • Show some (minimal) sample input and what you want as output. Commented Dec 18, 2012 at 6:47

5 Answers 5

1

Try :

 for(var i=0; i<lines.length; i++) {
        elements [i] = myFunction(lines[i]);
    }

I suppose it solves the problem.

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

1 Comment

Thanks this solved the problem. You just have to change lines[i] into lines[0]
1

You can use the Array concat function:

elements = elements.concat(myFunction(lines[i]));

2 Comments

actually concat returns an empty array
[].concat(['some-string']) equals ['some-string'], which I'm pretty sure is the desired output you described. Are you assigning the result of concat (it doesn't modify the array, it returns a new one)?
0

Presumably you want something like:

var arrs = [[0],[1,2],[3,4,5],[6]];
var result = [];

for (var i=0, iLen=arrs.length; i<iLen; i++) {
  result = result.concat(arrs[i]);
}

alert(result); // 0,1,2,3,4,5,6

Ah, you want to concatenate the results of a function. Same concept, see other answers.

Comments

0

You can also use myArray[myArray.length] = someValue;

1 Comment

Actually, that would assign the item outside of the bounds. myArray.length - 1 would be the index of the last element instead.
0
let newArray = [].concat(singleElementOrArray)

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.