concat empty / single item array - javascript

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 !

Try :
for(var i=0; i<lines.length; i++) {
elements [i] = myFunction(lines[i]);
}
I suppose it solves the problem.

You can use the Array concat function:
elements = elements.concat(myFunction(lines[i]));

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.

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

let newArray = [].concat(singleElementOrArray)

Related

Looping through items in an array of objects

I have an array of objects.
ABC.getAggregation("V")[0].getItems();
this produces the result:
MY ARRAY OF OBJECTS
In the console i can get the result i am looking for by specifying the position of the item like this:
ABC.getAggregation("V")[0].getItems()[0].getPosition()
ABC.getAggregation("V")[0].getItems()[1].getPosition()
ABC.getAggregation("V")[0].getItems()[2].getPosition()
The result of the above code produces string values e.g "3.4554,43,0".
How can i loop through each item and get the position in my code. just like the above code that i typed in the console. there wont always be 3 objects this is why i cant hard code the above 3 lines.
Try using a the Array.prototype.forEach() function. The function will be called for each element in the array, passing in the element as the first parameter.
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
item.getPosition();
//do something else
});
More on ".forEach()"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
You can treat it like any other array:
var myArray = ABC.getAggregation("V")[0].getItems();
for(var i=0; i< myArray.length; i++){
myArray[i].getPosition(); //Do something with the position.
}
You can use for loop to iterate trough all of them.
for(var i=0; i<ABC.getAggregation("V").getItems().length; i++) {
ABC.getAggregation("V")[0].getItems()[i].getPosition();
}
You can use forEach loop to iterate trough all of them.
ABC.getAggregation("V").getItems().forEach (item, index) {
return ABC.getAggregation("V")[0].getItems()[index].getPosition();
}
A very simple way to iterate through each object in the array is just with a for loop on the array, you don't even need to declare your iterating variable.
ex:
var anArray = ['one', 'two', 'three'];
for( i in anArray){
console.log('index #: ' + i );
console.log(anArray[i]);
}
will print out all the elements in anArray:
index #: 0
one
index #: 1
two
index #: 2
three
!! Apparently this is a good example of how not to do it :P
You can assign the items to an array and loop through them like this:
var items = ABC.getAggregation("V")[0].getItems();
var returnString = "";
for (var key in items ) {
if (items .hasOwnProperty(key)) {
var element = items [key];
returnString += element.getPosition() + ',';
}
}
returnString = returnString.substring(0, x.length-1);
console.log(returnString);

Array can't take values from variable

Hi I try run this code but I have on page in all this 35 fields value "undefined" I try print on screen this letters
ar letters_tab = new Array(35);
var letters = "AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUVWXYZŹŻ";
for(var i in letters)
{
letters_tab.push[i];
}
You can't iterate through a string using for..in like the way you demonstrate.
I'm not sure what you are trying to accomplish but here are a few options:
1. String.prototype.split
If you're just trying to get the string into a character array, this will do:
var letters_tab = 'AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUVWXYZŹŻ'.split('');
2. Manual iteration
If you want to manually iterate through the string to construct the array, you can also do so by using a plain old for loop:
var letters_tab = []; // alternatively, new Array()
var letters = "AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUVWXYZŹŻ";
for(var i = 0; i < letters.length; i++)
{
letters_tab.push(letters[i]);
}
3. for..of
You can also iterate a string using a for..of loop in modern JavaScript environments:
var letters_tab = []; // alternatively, new Array()
for (var i of 'AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUVWXYZŹŻ') {
letters_tab.push(i);
}
You can manually go through the strings and get characters from it and put it into your array.
try this:
var letters_tab = new Array(35);
var letters = "AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUVWXYZŹŻ";
for(var i=0; i < letters.length; i++)
{
letters_tab[i] = letters.charAt(i);
}
alert(letters.letters_tab);
Try this;
for (var letter in letters) {
letters_tab.push(letters[letter]);
}
That's because the variable letter is only the index, not the actual value.
You can also use the .split method.
var letters_tab = 'AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUVWXYZŹŻ'.split('');

How to work with multidimensional array when the number of dimension is variable?

Hello stackoverflow members.
I come with the following problem:
To start we have
var myArray = [[array1],[array2],[array3],[arrayN],...];
where each array is filled with a known number of strings such as
var array1 = ["a","b"], array2 = ["1","2"], array3=["&","é"];....
and so on.
I'm looking for a method to get this result:
expected result ===> a1&;a1é;a2&;a2é;b1&;b1é;b2&;b2é; ....
If the number of dimension were fixed I could use for loops to iterate and build the result, BUT here the problem is that I want to be able to enter N arrays in the main array myArray and by doing so, I change the depth of the nested loops.
If not do you have some ideas to put me on the track of the solution to this?
Thanks!
EDIT by the way this is what i experimented:
for (i=0; i<myArray[0].length; i++){
for (var j =0; j<myArray[1].length; i++){
for(var k = 0; k<myArray[2].length; k++{
console.log(i+j+k);
}
}
}
BTW i can't find a way to describe a function which would nest N for loops where N is myArray.length + 1 (the number of arrays in myArray).
EDIT: i found an iterative way of doing it and wanted to share the solution:JSFiddle
To get a flat list of all cells, something like the following recursive function should work (if you have a non-empty array of arrays, and all array items are strings):
function makeFlatList(inputArray) {
if (inputArray.length == 1) { // if this array has only one array inside
return inputArray[0]; // return the array inside
} else {
var outArr = [];
var arrayShifted = inputArray.slice(1); // remove first subarray from inputarray
var arrayShiftedFlat = makeFlatList(arrayShifted); // recursive call
for (var i=0; i<inputArray[0].length ; i++) { // loop over first array
for (var j=0; j<arrayShiftedFlat.length; j++) {
outArr.push(inputArray[0][i]+arrayShiftedFlat[j]); // add items to outArr
}
}
return outArr;
}
}
Working JSBin here

Javascript for loop var "i" is treated as a string?

I am using Titanium to build some mobile apps and I noticed that this will give a result that I wasn't expecting.
data = ['a','b', 'c','d'];
for (var i in data){
Ti.API.debug(i+1);
};
This will print: 01,11,12,13
Is this something particular to Titanium or is it generally in Javascript?
Why isn't 'i' being treated as an integer? I am very confused.
Thanks for your help.
This doesn't directly answer your question, but if you are looping through an array you should not use for (var i in data). This loops through all members of an object, including methods, properties, etc.
What you want to do is this:
for (var i=0, item; i<data.length; i++) {
item = data[i];
}
data is an array, so you use a for loop, not a for-in loop:
var data = [ ... ];
var i;
for ( i = 0; i < data.length; i += 1 ) {
Ti.API.debug( i + 1 );
}
Alternatively, you can use the forEach array method:
data.forEach( function ( val, i ) {
Ti.API.debug( i + 1 );
});
The reason why you see this behavior is that the type of i when using a for-in over an array is string not int. Hence the + is doing string concatenation and not addition. If you want it to be the numerical value then use a for loop
for (var i = 0; i < data.length; i++) {
Ti.API.debug(i + 1);
}
Try this:
data = ['a','b', 'c','d'];
for (var i in data){
Ti.API.debug(i*1+1);
};
Multiplying i x 1 will force it to recognize it as numeric.
Try this:
Ti.API.debug(parseInt(i)+1);
You can do
data = ['a','b', 'c','d'];
for (var i in data){
console.log(parseInt(i)+1);
};
But it is not recommended. Because in Javascript for..in loop is for key:value pairs (Objects). So if use it with an array each index is converted to string as key.
so always use for(i = 0; i < length; i++) with arrays.
This is because javascript handles for-each loop this way.
In other languages for(i in datas) will loop through each data.
But in javascript the i will have index value instead of data. so you have to get data by datas[i].

Elegant way to convert string of values into a Javascript array?

I have an ajax request that returns a list of values like this:
"1,2,3,4,5,6"
I need it to be a javascript array with numbers:
[1,2,3,4,5,6]
I tried:
var array = new Array("1,2,3,4,5,6".split(","))
But the numbers are still strings in the output:
["1","2","3","4","5","6"]
Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?
You need to loop through and convert them to numbers, like this:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];
Or, the more traditional example:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);
A more jQuery-centric approach using jQuery.map():
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });
Not sure if this counts as writing a function but you can use the map function in jquery. I saw you listed as a tag so I assume you are using:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
function(item, i)
{
return parseInt(item, 10);
});
// jquery must have a way to do what any modern browser can do:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);
// returns an array of numbers
If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");
If you don't wish to expliclty iterate you can use array.map, javascripts map function.
array.map(callbackFunc, array);
var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));
http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.
EDIT - i see jQuery has its own map, thats probably worth looking into.

Categories

Resources