Javascript - Adding new label and data to existing array - javascript

As I know, it is possible to push more data into an array. Fe, I have an array:
G = [12, 34, 5].
Right now, I can access the nth element like this:
G[n]
I'd now like to push new data in it with a label, so I want the array to look like
G = [12, 34, 5, label:567856, other: Infinity]
where I can get 567856 by calling
G["label"] //(or Infinity by calling G["other"]). How can I achieve this?
I've found
G[i].push({
label:567856,
other: Infinity
})
but this way it adds it as a whole new element, and I'm only able to call G[4]["other"], instead of G["other"]. How can I add the element as I've described?
Thank you!

To add onto Andriy's answer, you need to use Javascript Objects rather than arrays. An object can have indices with custom names. For example, given
var newObj = {"hello": "world", "value":1, "inf": Infinity}
you can do
newObj['hello'] // "world"
newObj['value'] // 1
The problem with
G[i].push({
label:567856,
other: Infinity
})
is that you are pushing an object with 2 attributes, not pushing 2 objects, that's why you need to use G[4]["other"]
See running JSFiddle example.

G["other"] = "something";
With this you will keep the original array, and now have the attribute other, but it is not in [12, 34, 5]
Whit this one you can add an object to the array:
G.push({other: 123})
console.log(G);//[12, 34, 5, object]
console.log(G[3].other);//123
The problem with
G[i].push({
label:567856,
other: Infinity
})
is that you are pushing an object with 2 attributes, not pushing 2 objects, that's why you need to use G[4]["other"]

Arrays in JavaScript are a type of object. As such, they can contain properties:
G.label = 567856;
G.other = Infinity;
The advantage of arrays over other objects is that their indexed elements are ordered.
If you'd like the fourth and fifth elements in the array to be 567856 and Infinity and you want to be able to refer to those values with G.label and G.other, you can do so as follows:
var G = [12, 34, 5];
G.push(G.label = 567856); //same as G.label = 567856; G.push(G.label);
G.push(G.other = Infinity);
You can still iterate through the array using a loop:
var G = [12, 34, 5];
G.push(G.label = 567856);
G.push(G.other = Infinity);
G.forEach(function(val) {
console.log(val); // 12 ... 34 ... 5 ... 567856 ... Infinity
});
console.log(G.label); //567856
console.log(G.other); //Infinity
Note that this does create duplicates. If you change G.label or G.other afterwards, those changes will not be reflected in the fourth and fifth elements of the array.
However, you can overcome that by creating setters on G.label and G.other using Object.defineProperty():
var G = [12, 34, 5];
G.push(G.label = 567856);
G.push(G.other = Infinity);
G.forEach(function(val) {
console.log(val); // 12 ... 34 ... 5 ... 567856 ... Infinity
});
console.log(G.label); //567856
console.log(G.other); //Infinity
Object.defineProperty(G, 'label', {
set: function(x) {
this[3] = x;
}
});
Object.defineProperty(G, 'other', {
set: function(x) {
this[4] = x;
}
})
G.label = 99999;
G.other = 11111;
G.forEach(function(val) {
console.log(val); // 12 ... 34 ... 5 ... 99999 ... 11111
});

Arrays isn't designed to suit your case.
See Array element accessing flow from ECMAScript 262, 5.1 15.4
Array objects give special treatment to a certain class of property
names. A property name P (in the form of a String value) is an array
index if and only if ToString(ToUint32(P)) is equal to P and
ToUint32(P) is not equal to 2^32−1.
So you simply cannot access Array element by alphabetical name because that key won't be parsed to integer by ToUint32.
You can add object to array and store it's index after pushing into array ( Array.prototype.push would return you size of your array):
var G = [1,3,4];
var labelIndex = G.push({'label': 123}) - 1;
console.log(G[labelIndex]["label"]);
Actually that's solution would suite case when you have two or more objects inside your array with same property.
Suggestion below not recommended!
However, you can use code below to define your G Array properties, but it's not value of property of item from your array, it's array property:
G.other = Infinity;
G.label = 567856;
// Access newly created properties
console.log(G["other"]);
console.log(G["label"]);
Good Luck !

Related

Counting variables in for loops [duplicate]

What is the difference between the two?
So I know that array.size() is a function while array.length is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?
var x = [];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
x =[1,2,3];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
Will print:
0, 0, true
3, 3, true
Array.size() is not a valid method
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
.size() is not a native JS function of Array (at least not in any browser that I know of).
.length should be used.
If
.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.
or
There might be some plugin on your browser that is mucking with the Array prototype.
The .size() function is available in Jquery and many other libraries.
The .length property works only when the index is an integer.
The length property will work with this type of array:
var nums = new Array();
nums[0] = 1;
nums[1] = 2;
print(nums.length); // displays 2
The length property won't work with this type of array:
var pbook = new Array();
pbook["David"] = 1;
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0
So in your case you should be using the .length property.
.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.
If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.
array.length isn't necessarily the number of items in the array:
var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101
The length of the array is one more than the highest index.
As stated before Array.size() is not a valid method.
More information
The property 'length' returns the (last_key + 1) for arrays with numeric keys:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
log.info( nums.length );
will print 12!
This will work:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
nums [ 12 ] = 12 ;
log.info( nums.length + ' / '+ Object.keys(nums).length );
The .size() method is deprecated as of jQuery 1.8. Use the .length property instead
See: https://api.jquery.com/size/
Size detects duplicates, it will return the number of unique values
const set1 = new Set([1, 2, 3, 4, 5, 5, 5, 6]);
console.log(set1.size);
// expected output: 6
Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.
The size accessor property returns the number of (unique) elements in a Set object.
const set1 = new Set();
const object1 = new Object();
set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);
console.log(set1.size);
// expected output: 3
And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4
we can you use .length property to set or returns number of elements in an array. return value is a number
> set the length: let count = myArray.length;
> return lengthof an array : myArray.length
we can you .size in case we need to filter duplicate values and get the count of elements in a set.
const set = new set([1,1,2,1]);
console.log(set.size) ;`

Access array inside an object

var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
I want to access array in object b. ie, maths, physics, chemistry .
This may be a simple question but i am learning....Thanks
Given the arrays in the object b (note that you have a syntax error in the code you provided)
var b = {
maths: [12, 23, 45],
physics: [12, 23, 45],
chemistry: [12, 23, 45]
};
maths, physics, and chemistry are called properties of the object stored in variable b
You can access property of an object using the dot notation:
b.maths[0]; //get first item array stored in property maths of object b
Another way to access a property of an object is:
b['maths'][0]; //get first item array stored in property maths of object b
var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
console.log(b.maths);
// or
console.log(b["maths"]);
// and
console.log(b.maths[0]); // first array item
var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
// using loops you can do like
for(var i=0;i<b.maths.length;i++){
console.log(b.maths[i]);//will give all the elements
}
there are simple:
b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
b.maths[1] // second element of maths
b.physics
b.chemistry
You need to set the variable b like this :
var b = {
maths:[12,23,45],
physics:[12,23,45],
chemistry:[12,23,45]
};
Then you can access your arrays inside b by using b.maths, b.physics and b.chemistry.

Get the top ten vars with the highest value in Javascript

Basically I have about 36 variables that are named t0, t1, t3 ... and so on, each variable is initiated with the value 0, and depending on actions they get incremented by 1.
I want a way to be able to list the top ten highest valued variables ideally by putting them in an array like Var topTen = [t33,t31,t2].
Why don't you use an object to store the information - instead of 36 variables have just one object with 36 properties. Then you can loop through the values, add them to an array and grab the set of numbers you need:
var obj = {
t1: 1,
t2: 33,
t3: 10,
t4: 9,
t5: 45,
t6: 101,
...
}
// create an array
var arr = [];
// loop through the object and add values to the array
for (var p in obj) {
arr.push(obj[p]);
}
// sort the array, largest numbers to lowest
arr.sort(function(a,b){return b - a});
// grab the first 10 numbers
var firstTen = arr.slice(0, 9);
This will return an array - just loop through it to list the values one by one.
DEMO
Should try this method :
var myarray=["t14", "t53", "t1"]
myarray.sort();
myarray.reverse();
var final = myarray.slice(0,10);
//SHOULD GIVE YOU
// ["t53", "t14", "t1"]
Then you can extract the ten first value.
UPDATE --> JSFiddle
res = [{k:"t1",v:t1},{k:"t2",v:t2},...,{k:"t36",v:t36}].sort(
function(a,b){
return b.v-a.v
}).map(function(x){return x.k}).slice(0,9)
btw. you can create the array dynamically if the variables are represented as object properties...
if you need the values, then return x.v instead of x.k
First put the variables in an array:
var ts = [t0, t1, ...];
You can then get the top 10 like this:
var topTen = ts.sort().slice(-10).reverse();
Ideally you want store all your values in an array in the first place.
Sort your array after that slice first 10 elements.
arr.sort(function (a,b) {
return a - b;
});
var result = arr.slice(0,10);

Should I use curly brackets {} or square brackets [] in this case?

Currently I have an array using an increasing index:
var idx = 1;
var a = [];
a[idx++] = "apple";
a[idx++] = "orange";
...
console.log(a[2]);
And only accessing it by [], not using array specific functions, like length, indexOf, ...
Apparently following is also working in this case:
var a = {};
So, which one should I prefer in such case? For example any performance difference between them?
[ ] denotes an array. Arrays only hold values:
var a1 = [1, 2, 3, 4]
As #Qantas pointed out, array can hold more than just values. An array can even contain another array and/or object:
var a2 = [1, 2, ["apple", "orange"], {one: "grape", two: "banana"}];
{ } denotes an object. Objects have key-value pairs like
var a3 = {one: 1, two: 2}
In your case, it's really a matter of how you would like to be able to access the data. If you are only interested in knowing "apple", "pear", etc. Go ahead and use an array. You can access it via it's index
a1[0]; // outputs 1
a1[1]; // outputs 2
or you can iterate over it with a loop. If you use the curly braces, (given the example I gave) you could access it with
a3.one; // outputs 1
a3["two"]; // outputs 2
It's really up to you on how it would best fit your needs in this case. For a more extensive discussion see this article.
The difference is using square brackets will create an Array object while using curly brackets creates a plain object. For example:
a = [];
a[1] = 'a';
b = {};
b[1] = 'b';
a.length; // returns 2
b.length; // is undefined
a.push('z'); // add 'z' to the end of a
b.push('z'); // generates an error - undefined is not a function
// because plain objects don't have a push method
Read the MDN documentation on Array objects to know more about arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Array.size() vs Array.length

What is the difference between the two?
So I know that array.size() is a function while array.length is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?
var x = [];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
x =[1,2,3];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
Will print:
0, 0, true
3, 3, true
Array.size() is not a valid method
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
.size() is not a native JS function of Array (at least not in any browser that I know of).
.length should be used.
If
.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.
or
There might be some plugin on your browser that is mucking with the Array prototype.
The .size() function is available in Jquery and many other libraries.
The .length property works only when the index is an integer.
The length property will work with this type of array:
var nums = new Array();
nums[0] = 1;
nums[1] = 2;
print(nums.length); // displays 2
The length property won't work with this type of array:
var pbook = new Array();
pbook["David"] = 1;
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0
So in your case you should be using the .length property.
.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.
If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.
array.length isn't necessarily the number of items in the array:
var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101
The length of the array is one more than the highest index.
As stated before Array.size() is not a valid method.
More information
The property 'length' returns the (last_key + 1) for arrays with numeric keys:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
log.info( nums.length );
will print 12!
This will work:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
nums [ 12 ] = 12 ;
log.info( nums.length + ' / '+ Object.keys(nums).length );
The .size() method is deprecated as of jQuery 1.8. Use the .length property instead
See: https://api.jquery.com/size/
Size detects duplicates, it will return the number of unique values
const set1 = new Set([1, 2, 3, 4, 5, 5, 5, 6]);
console.log(set1.size);
// expected output: 6
Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.
The size accessor property returns the number of (unique) elements in a Set object.
const set1 = new Set();
const object1 = new Object();
set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);
console.log(set1.size);
// expected output: 3
And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4
we can you use .length property to set or returns number of elements in an array. return value is a number
> set the length: let count = myArray.length;
> return lengthof an array : myArray.length
we can you .size in case we need to filter duplicate values and get the count of elements in a set.
const set = new set([1,1,2,1]);
console.log(set.size) ;`

Categories