Two dimensional arrays populating does not work javascript - javascript

When i try to create two dimensional array in javascript using loop, it gives me following error:
Cannot set property 'indexis' of undefined
Code:
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
}
}

You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
indexes[i] = {}; //<---- need this
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i];
indexes[i]['valueis'] = rows[0][i];
}
}
You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']

You need an object before accessing a property of it.
indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;

define temp var with field initialise to null & use push() function of JavaScript
for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
if (headingsArray) {
temp['indexis'] = i;
temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
temp['valueis'] = rows[0][i];
indexes.push(temp);
}
}

Related

Using two separate objects, I would like to return an object with the matching key, value pairs?

I have created three functions, that can make two separate arrays with the matching keys and the matching properties. I would like to use those two arrays to create a new object with all of the matching pairs. Below I included the functions I have so far.
I am a beginner in Javascript ( which is most likely already apparent) so if you can explain each step thoroughly and not get to complex I would greatly appreciate it.
function contains(array, obj_to_check){
for(var i = 0; i < array.length; i ++) {
if (array[i] == obj_to_check) {
return true;
}
}
}
function sharedKeys(obj1, obj2) {
var obj1Keys = Object.keys(obj1);
var obj2Keys = Object.keys(obj2);
var sharedArray = [];
for( var x = 0; x < obj1Keys.length; x++){
if (contains(obj2Keys, obj1Keys[x])){
sharedArray.push(obj1Keys[x]);
}
}
return sharedArray;
}
function sharedProperties(obj1, obj2) {
var obj1Props = [];
var obj2Props = [];
var propertiesArray = [];
for(var i in obj1)
obj1Props.push(obj1[i]);
for(var x in obj2)
obj2Props.push(obj2[x]);
for (var y = 0; y < obj1Props.length; y ++){
if(contains(obj1Props, obj2Props[y])){
propertiesArray.push(obj2Props[y])
}
}
return propertiesArray;
}
You are comparing two objects, not two values. The only way that your == comparison works here is if both of them refer to the same object. You need to check and see if every properties and fields of those two objects are equal. Besides, check this thread about comparison in JavaScript.

How to create a multidimensional array in JavaScript?

How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}

Combine object value

My jquery array is showing like
[Object { qty=1, item_id="76", add_ons="2", add_on_price:20}, Object { qty=1, item_id="76", add_ons="1",add_on_price:40}]
I want to make an array like this
[object{ qty=2,item_id=76,add_ons_price=60}]
I need to add the qty,add_ons_price in single object.
any help will be appreciated.
this will group objects based on property item_id
var result = {};
for (var i = 0, len = myObjects.length; i < len; i++) {
var obj = myObjects[i];
if (result[obj.item_id] === undefined) {
result[obj.item_id] = [];
}
result[obj.item_id].push(obj);
}
now you can add the required values and push the result in new object

How to prototype a duplicate prototype method for Array in javascript

I'm trying to implement a duplicate method to the js Array prototype which concats a duplicate of the array to itself like so:
[11,22,3,34,5,26,7,8,9].duplicate(); // [11,22,3,34,5,26,7,8,9,11,22,3,34,5,26,7,8,9]
Here's what I have, but it causes the browser to crash:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var j = this.length;
for(var i = 0; i < this.length; i++) {
this[j] = this[i];
j++;
}
return this;
}
I'm trying to do this using native JS as practice for iterations and algorithms so I'm trying to avoid built-in methods, if possible, so that I can get a clearer understanding of how things are being moved around.
Any ideas on why it is crashing and how I can optimize it?
The code inside the loop changes the length of the array, so it will just keep growing and you will never reach the end of it. Get the initial length of the array in a variable and use in the loop condition. You can use that as offset for the target index also instead of another counter:
var array = [11,22,3,34,5,26,7,8,9];
Array.prototype.duplicate = function() {
var len = this.length;
for (var i = 0; i < len; i++) {
this[len + i] = this[i];
}
return this;
}
The length of the array is increasing with each element added so you can not use this as a terminator. Try this.
var j = this.length;
for(var i = 0; i < j; i++) {
this[i+j] = this[i];
}
Here's simplest code
Array.prototype.duplicate = function () {
var array = this;
return array.concat(array);
};
Using Spread syntax;
In a method, this refers to the owner object.
Array.prototype.duplicate = function () {
return [...this, ...this]
};
let array = [1,2,3,4,5];
Array.prototype.duplicate = function () {
return [...this, ...this]
};
console.log(array.duplicate());

Add values to an array

How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'
var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}
In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);
You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object
Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);

Categories