Loop thought a multi dimensional array - javascript

I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic
const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i], thirdInterval[i+1])
}
The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.

What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])
to access the first and second elements you should address them like the following:
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}

const arr = [[1,2][3,4][5,6]];
for (var i = 0; i < arr.length; i++;) {
func(arr[i][0], arr[i][1];
}

You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).
In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.
Demo:
const thirdInterval = [[1,2],[3,4],[5,6]]
const getNumbers = console.log // mock getNumbers
for (let i = 0; i < thirdInterval.length; i++) {
getNumbers(...thirdInterval[i])
}

Related

Create array with function javascript

I need to create function that creates and returns array. Its size needs to match the rows parameter, and each next element contains consecutive integers starting at 1. To call this function I need to use argument 5. Here below is what I wrote so far. Can you tell me what's wrong here?
function createArray(rows) {
for(let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}return rows;
}
createArray(5);
You need to create an array and return it, whereas you return just rows which is a number. The idea of using a for loop is the best way to go. In that loop you just need to set the values in the array accordinlgy.
Another problem in your code is that rows is of type number and does have a property length but that does not have the desired value. So we just use rows in the for loop. We start the loop with i = 0 because array indices start at 0.
Code
function createArray(rows) {
let arr = new Array(rows);
for (let i = 0; i < rows; i++) {
arr[i] = i + 1;
}
return arr;
}
console.log(createArray(5));
We can not use length property for number. create an empty array and then push values into that array until required size is achieved.
function createArray(rows) {
var arr = [];
for(let i = 1; i <= rows; i++) {
arr.push(i);
}return arr;
}
createArray(5);
I think what you want is createArray(5) return [1,2,3,4,5] if that's the case you could do this
function createArray(rows) {
const arr = []
for(let i = 1; i <= rows; i++) {
arr.push(i);
}
return arr;
}
console.log(createArray(5));
The problem is, that rows.length is not available on 5, because 5 is a number.
You have to use an array as parameter:
Array(5) creates an array with the length of 5 and fill("hello") fills this array with "hello" values.
function createArray(rows) {
for (let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}
return rows;
}
const rows = Array(5).fill("hello");
createArray(rows);
I don't know, if this is the behaviour you want, if not, I misunderstood your question.

new to javascript, working with arrays

Wondering why i needed to add 4 to the array length in order for it to print out the entire array in reverse?
before i added 4 it was just using the .length property and it was only printing out 6543.
thanks in advance!
function reverseArray(array) {
var newArray =[];
for(var i = 0; i <= array.length+4; i++) {
newArray += array.pop(i);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
array.pop removes (and returns) the last element. This affects the length of the array. The length is checked on every iteration, so since the array is getting shorter every time, the loop is ended early.
You can create a loop and pop items until it is empty, but another thing to take into account, is that it is the original array you are altering. I think a function like reverseArray shouldn't alter the array numbers that was passed to it if it returns another one. So a better solution would be a simple loop that iterates over all items without modifying the array.
function reverseArray(array)
{
var newArray =[];
for (var i = array.length-1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));
console.log(numbers); // Should be unaltered.
If you don't mind modifying the array, you can use the reverse() method of the array:
var numbers = [1,2,3,4,5,6];
numbers.reverse();
console.log(numbers);
In Javascript, pop always removes the last element of the array. This shortens length, meaning that i and array.length were converging.
You can do a few things to avoid this behavior:
Store the original length when you start the loop: for (var i = 0 , l = array.length; i < l; i++)
Copy over values without modifying the original array
When you pop the items from the array, the item is removed from the array. As you increase the counter and decrease the length, they will meet halfway, so you get only half of the items.
Use push to put the items in the result. If you use += it will produce a string instead of an array.
If you use pop, then you can just loop while there are any items left in the array:
function reverseArray(array) {
var newArray = [];
while (array.length > 0) {
newArray.push(array.pop());
}
return newArray;
}
You can leave the original array unchanged by looping through it backwards and add items to the new array:
function reverseArray(array) {
var newArray = [];
for (var i = array.length - 1; i >= 0; i--) {
newArray.push(array[i]);
}
return newArray;
}
use following method for same output
function reverseArray(array)
{
var newArray =[];
var j = array.length-1;
for(var i = 0; i < array.length; i++)
{
newArray[j]= array[i]; j--;
}
return newArray;
}
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

Push is not a function JavaScript error

In the below code, I am getting "push is not a function" error. Can anyone please let me know what I am doing wrong here? I am trying to create 2D array in Javascript.
var myArray = new Array(4);
myArray = ["0","0","0","0"];
for (var i=0; i<myArray.length; i++) {
myArray[i].push("ID");
myArray[i] = new Array(1);
for (var j=0; j<myArray[i].length; i++) {
myArray[i][j].push("Array[j]");
}
}
Firebug is pointing me to:
myArray[i].push("ID");
For this line I am getting "TypeError: myArray[i].push is not a function"
Final array it should look like is:
[ID,"SomeValue1"],
[ID,"SomeValue2"],
[ID,"SomeValue3"]
And I cannot hard code, I need to create this dynamically based on data from DB
myArray[i].push("ID");
Is invalid of course because it's a function defined for an Array not for it's elements.
valid syntax would be
myArray.push("ID");
To know more about array.push() go here.
This will create your example.
var myArray = new Array(4);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", "SomeValue" + (i+1)];
}
But if you need to set data from a database, how is that being set in the Javascript? if it's in a different array you could do the following:
var dbArray = ["SomeValue1", "SomeValue2", "SomeValue3"];
var myArray = new Array(dbArray.length);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", dbArray[i]];
}
First of all, you can initialize Arrays using the Array Literal [] which should always be preferred
Then push is an Array method. So you have to call it on an Array
myArray[i] is the Element of the Array, myArray the Array
var arr = [];
for (var i = 0; i < 5;i++) {
arr.push = []; //Uses the Arrays push method
for ( var j = 0; j < 5; j++)
arr[i][j] = "Asd"; //Sets an Element
}
console.log(arr);
And as you see don't need to "Dim" an Array, you just can assign an Array to a Variable and start pushing Elements in it.
As you can see in the example, the first time
push is directly after arr, its the Arrays Method and appends a new Element to the Array
And in the second Example it accesses the Element and assigns it a value directly
What you are doing in your code is trying to invoke the push method on an Elements Array
Assume i is 0 Then
'myArray[i]' is "0" and the String "0" has no Method push.
But you can directly assing a new String to the Element like.
myArray[i] = "ID"

Javascript : How should I run one `for`, for two arrays?

I have:
var array1 = [];
var array2 = [];
array1 contains 1,2
array2 contains 3,4
And I want to do this:
for(var a in array1){
for(var b in array2){
doSomething(array1[a],array2[b]);
}
}
But the problem is that function doSomething() runs twice for each array because of the two for's.
How should run it just once but with all of the arrays?
EDIT
The numbers are not in ascending order! In my real project they are ID's what can be any number in any order.
You shouldn't use for..in for looping through arrays. Use an index variable:
for (var i = 0, len = array1.length; i < len; i++) {
doSomething(array1[i], array2[i]);
}
This of course assumes they're the same length.
I think this is what you're after:
for(var i=0; i<array1.length; i++){
doSomething(array1[i],array2[i]);
}
This loops through both arrays, using the first for the length, and taking the element at the same index in both for each doSomething() call.
If you are sure that both arrays have the exact same length, you can do the following:
for (var i = 0; i < array1.length; i++) {
doSomething(array1[i], array2[i]);
}
It looks like you want to concatenate two arrays together. Use the concat() function:
var jointArray = array1.concat(array2);
for(var i=0; i < jointArray.length; i++) {
doSomething(jointArray[i]);
}
See:
http://www.w3schools.com/jsref/jsref_concat_array.asp
This if array arent same length
for (var i = 0, i < (array1.length <= array2.length ? array1.length : array2.length); i++) {
doSomething(array1[i], array2[i]);
}
DoSomething will run 4 times. If you want it to just run through the values both list together, remove the second for loop and replace b in DoSomething with a.

Categories

Resources