Push is not a function JavaScript error - javascript

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"

Related

Loop thought a multi dimensional array

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])
}

I have written this code but it is not showing any outputs. Why is this happening?

I have written this code but I am completely not sure the way I did is correct. Is there anyone that can give me some guidance?
Create a variable named numbers and assign an empty array to it.
Using a for-loop and the Array.push() method, insert the numbers 0 to 9 into the array you named numbers.
Test that you used the Array.push() method correctly by console logging the first item in the array.
Console log the last item in the array.
Create another variable named car and assign an empty object to it.
Give the object a property called colour and assign it the value of "black".
var numbers = [];
for (var i=0; i < 10; i++){
numbers.push(i);
console.log(i[1])
console.log(i[9])
}
var car = {};
You have pushed numbers to an array numbers, but after this you have mixed up variables numbers and i. Variable i is not an array. Except this your console.log is in the for loop and this is mistake too.
I have corrected your code:
var numbers = [];
for (var i = 0; i < 10; i++){
numbers.push(i);
}
console.log(numbers[1]); //1
console.log(numbers[9]); //9
var car = {};
car.colour = 'black';
console.log(car.colour); //black
var numbers = [];
for(var i=0; i<10; i++) {
numbers.push(i)
}
console.log(numbers[0]);
var lastIndex = numbers.length - 1;
console.log(numbers[lastIndex]);
var car = {};
car.colour = 'black';

Array data split

I don't know if i am doing the array add by a correct method.
for (var i=0; i < result.length; i++){
var a = Array();// loop against the Data array on each object in result
var b = Array();
a.push(result[i].data.mentionTotal);
b.push(result[i].profileName);
mentionArr.push(b+a);
}
The for loop above gave a result like this :
[["orange1494"],["ansontest231403"],["happyboy0"],["babygirl0"]]
But i want to split the data so i tried to do:
mentionArr.push(b+'","'+a);
In order to split it but the outcome is like :
["orange\",\"1494","ansontest23\",\"1403","happyboy\",\"0","babygirl\",\"0"]
Which i am not able to use this array to do my task.
How may i solve it to:
[["orange","1494"],["ansontest23","1403"],["happyboy","0"],["babygirl","0"]]
Use:
for (var i=0; i < result.length; i++){
var a = [];
a.push(result[i].data.mentionTotal);
a.push(result[i].profileName);
mentionArr.push(a);
}
You dont need to create two arrays. Everytime the for loop runs a will initialize as a new array.
You just need to replace one line (mentionArr.push(b+a); to mentionArr.push([b,a]);) so you generate a new array with a and b in it instead of concatinating the two values:
for (var i=0; i < result.length; i++){
var a = Array();// loop against the Data array on each object in result
var b = Array();
a.push(result[i].data.mentionTotal);
b.push(result[i].profileName);
mentionArr.push([b,a]);
}

How to access array within an object within an array?

I have both an object and an array:
var elementsArr = [];
var elements = {
polygon: 734,
infoContent: "huhu",
id: 0
}
I am going to have multiple "elements" and push each one into "elementsArr".
for(var i=0; i<20; i++){
elements.id = id +=1;
elementsArr.push(elements);
}
My problem now is how to access a specific "id" within the object elements, within the array elementsArr and pushing this into another array.
I tried this but it doesn't seem to be working:
var ids = [];
for(var m=0; m<elementsArr.length; m++){
if(elements.id == elementsArr[m]){
ids.push(elements.id);
}
How do I do this?
Your code is pushing the same object onto the array over and over again.
One way to fix that would be to write a function to get a new element:
function Element(id) {
return {
polygon: 734,
infoContent: "huhu",
id: id
};
}
for(var i=0; i<20; i++){
elementsArr.push(Element(i));
}
If there are going to be a lot of elements, and the "id" values are all relatively small numbers, you'd be better off storing the elements such that the "id" is also the index:
for (var i = 0; i < 20; i++)
elementsArr[i] = Element(i);
To get the element with "id" 17, then:
var element17 = elementsArr[17];
If you really want to search, however, you can use .find():
var element17 = elementsArr.find(function(elem) { return elem.id === 17; });
or a simple loop:
for (var i = 0; i < elementsArr.length; ++i) {
if (elementsArr[i].id === 17) {
// found it!
}
}
You can extract the "id" values from the array with a simple call to .map():
var ids = elementsArr.map(function(elem) { return elem.id; });
or another for loop:
var ids = [];
for (var i = 0; i < elementsArr.length; ++i)
ids.push(elementsArr[i].id);
There are a couple of ways to do this. If you are able to work in ES6 then a WeakMap would be great.
However, I'm going to give you an ES5 instead.
Option 1 Loop through the data.
If you aren't accessing the data often, then looping through as you've done so may be the best choice.
Option 2 Set up your own index
On the other hand, if you need faster lookup, you can set up your own separate index to look things up.
var elementsLookup = {}; // Create an empty object.
for(var i=0; i<20; i++){
elements.id = id +=1;
elementsLookup[id] = elements; // Stash off a copy
elementsArr.push(elements);
}
Then you can look things up with a
var elem = elementsLookup[2]; // Get the element with an id of 2.
It is easy to do it with Array prototyping. Here is a function findById
Array.prototype.findById = function(id){
for(var x = 0 ; x < this.length; x++){
if(this[x].id == id){
return this[x];
}
}
return false;
}
You can use this function to recieve any id from the array or false if it does not exists
elementsArr.findById(17);

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);

Categories

Resources