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
}
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.
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.
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".
Related
Yes I know how to loop through arrays (types) in Javascript. The fact is, I'd like to know how to set a multiDimensionalArray array's value by a set of given indexes to keep it as generic as possible. For example I've an array with a length of 3 (which could as well be a length of 4, 100, ...):
var indexes = [0, "title", "value"];
I know the multidimensional array (mArray) can be set by putting the indexes like so:
multiDimensionalArray[0]["title"]["value"] = "Jeroen"; or multiDimensionalArray[indexes[0]][indexes[1]][indexes[2]] = "Jeroen";
The fact that the given indexes array can vary and does not always contain the same index names so I'm search for a solution like this:
multiDimensionalArray[indexes] = "Jeroen";
I don't know how to code the assignation if this. I've searched on Google/Stack Overflow. Maybe I'm using the wrong keywords. Can anyone help me?
Thanks!
Following example is how I've made it working thanks to Jonas's example:
var json = [{
"hello": {
"world": 1,
"world2": 2
},
"bye": {
"world": 1,
"world2": 2
}
}];
var indexes = [0, "hello", "world2"];
var value = "value";
indexes.slice(0,-1).reduce((obj, index) => obj[index], json)[indexes.pop()] = value;
console.log(json);
So imagine you have a structure like this:
var array=[[["before"]]];
Then you want
var indexes=[0,0,0];
var value="value";
to actually do:
array[0][0][0]="value";
which can be easily achieved with reduce:
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
Explanation:
indexes.slice(0,-1) //take all except the last keys and
.reduce((obj,index)=>obj[index] //reduce them to the resulting inner object e.g. [0,0] => ["before"]
,array) //start the reduction with our main array
[indexes.pop()]=value;// set the reduced array key to the value
var array=[[[0]]];
var indexes=[0,0,0];
var value="value";
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
console.log(array);
I have a two-dimensional array in Google apps script that contains arrays of different lengths. I would like to set the values of the array in a spreadsheet. However, because the arrays inside it are different lengths, I receive an error that essentially says the range and the array height don't line up. I've listed an example of the structure of the array below.
I can make it work if I add empty values to each individual array so that they all match the length of the longest array. This seems like a workaround though. Is there another way that I can set the values of the two-dimensional array?
var array = [
[a],
[b,c],
[d,e],
[],
[f,g,h,i],
[],
[j,k],
]
No, you cannot. The dimensions must match.
What you can do if you have few "rows" with great length difference, is to set each row on it's own.
for( var i = 0; i < array.length; ++i )
sheet.getRange(i+1, 1, 1, array[i].length).setValues([array[i]]);
But that's just another workaround. But working on your array to make all lengths match and do a single setValues will probably perform better.
In case your real array has many rows, individual writes will be expensive. Redimensioning each row array is fairly straightforward due to the way js handles arrays. A pattern similar to one i use is:
function myFunction() {
var array = [
[1],
[2,2],
[3,5],
[],
[0,0,0,0],
[],
[0,0],
];
// get length of the longest row
var max = array
.slice(0)
.sort(function (a,b) {
return ( (a.length !== b.length) ? 1 : 0 );
})[0].length;
// arrays are zero indexed
var maxi = max-1;
// insert a pointer at max index if none exists
array = array
.map(function (a){
a[maxi] = a[maxi] || "";
return a;
});
Logger.log(array);
}
Array1 = ['1,2,3']
How can I retrieve the numerical values by transforming it into non-string?
I've been trying parseInt, but I can only manage to get 1 as end-result.
Thanks.
If you start with an array containing a string, like in your example, you need to use split().
Example:
Array1 = ['1,2,3'];
var new_array = Array1[0].split(','); // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]
I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?
If you can, re-work your design to actually use an array of integers, so use:
var arr = [1,2,3];
instead of ['1,2,3'].
If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:
var array1 = ['1,2,3', '4,5,6,7'];
function as_int_array(list, index) {
return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]
Hope that helps.
Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.
Why you are getting 1 !!!
Whenever you are using parseInt() it tries to read your input character by character. So according to your input
var Array1 = ['1,2,3'];
first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.
Solution of your problem :
var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);
How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
If it's a simple array var newArray = new Array(); I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1] or myArray[0,1])?
You can create a 6 x 6 empty array like this:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6) generates an array with length = 6 and full of undefined values.
We map that array to another array full of undefined values.
In the end, we get a 6x6 grid full of undefined positions.
If you need to initialize the grid with a default value:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'.
Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript. Check out jsFiddle Live Demo
Define:
const arr = [[],[]];
Push data:
arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';
Read data:
alert(arr[0][2]);
alert(arr[1][3]);
Update:
Here is also a video recommended by Brady Dowling:
Create a 2D array: ([https://www.youtube.com/watch?v=tMeDkp1J2OM][2])
There are no two dimensional arrays in Javascript.
To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).
An empty jagged array is created just like any other empty array:
var myArray = new Array();
You can also use an empty array literal:
var myArray = [];
To put any items in the jagged array, you first have to put inner arrays in it, for example like this:
myArray.push([]);
myArray[0][0] = 'hello';
You can also create an array that contains a number of empty arrays from start:
var myArray = [[],[],[]];
That gives you a jagged array without any items, but which is prepared with three inner arrays.
As it's an array of arrays, you access the items using myArray[0][1].
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's.
Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.
You can use a simple for loop to create an array of the approximate size and then push more rows if need be.
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
console.log(arr);
var myArray = [
["cats","dogs","monkeys","horses"],
["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
Two things:
1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.
A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.
2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.
See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/
Here is a copy of that code:
var arr = [[],[]];
alert( arr.length ); // wrong!
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c ); // correct
arr[0][2] = 'Hi Mr.A';
alert(arr[0][2]);
arr[1][3] = 'Hi Mr.B';
alert(arr[1][3]);
arr[2][4] = 'Hi Mr.C'; // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
alert(arr[2][4]);
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c );
Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?
Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.
Thanks.
The functions I use
function get_empty_2d_array(numRows, numColumnns) {
return [...Array(numRows)].map(e => Array(numColumnns));
}
function get_2d_array_filled(numRows, numColumnns, fillValue) {
return [...Array(numRows)].map(e => Array(numColumnns).fill(fillValue));
}
This also works as an expression:
var twoDarr= new Array(desiredLength);
for (i=0;i<twoDarr.length;i++) {twoDarr[i]=[];}
I don't know how it pars in terms of performance with the rest of the answers here, if you have a clue let me know in the comments.
If you don't know the length of the array beforehand pls have in mind that you can use either push([]), or splice() if you want to push/remove/replace a new element in place of an existing one.
const grid = new Array(n).fill(new Array(n))
Simple javascript question:
I have an array (50=50; 49=49; 143=143; 4005=4005; ... )
which i want to turn into (50; 49; 143; 4005; ...).
The name will always be the same as the value, in the name=value pair.
It will always be a number (but of various lengths).
I just cant get my head around it using .split
Thanks
Assuming that you mean you have an array like this:
var arr = ['50=50;','49=49;','143=143;','4005=4005;'];
Then, you may employ split like this:
var newArr = [], ii;
for (ii = 0; ii < arr.length; ii += 1) {
newArr.push(parseInt(arr[ii].split('=')[0], 10));
}
This will result in newArr being equal to this:
var newArr = [50, 49, 143, 4005];
The way split works is it divides a string up into an array based on a delimiter string. In this example, we've used '=' as the delimiter, so we end up with arrays like this:
['50', '50;']
['49', '49;']
// etc.
Then, index into the first element and pass it to parseInt to produce a number, and push onto a new array with just number elements.
Here's a working example.
Addendum
If you aren't starting with an actual JavaScript array, but a string that you'd like to turn into an array, then add this step before the previous ones to get yourself the original array:
var str = '(50=50; 49=49; 143=143; 4005=4005;)';
var arr = str.replace(/\(|\)|;/g, '').split(' ');