Access array inside an object - javascript

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.

Related

Map having keys as objects

The documentation on Map on mdn says
A Map's keys can be any value (including functions, objects, or any primitive).
Let's say we have
let a = new Map();
a.set({a: 1, b:3}, "Hello");
a.set({a: 1, b:3}, "World");
This produces a map with 2 elements instead of one.
How can I make the lookup of keys to be in terms of their values and not their ids?
Or alternatively, how can I make a Map where the key is a pair of unordered values?
The following is a workaround that will store things in the way you intend. Albeit, it does not use the Map class and the assigning function is not a method of any class.
set=function(a,o,v){a[[o.a,o.b].sort().join(",")]=v};
const a = {};
set(a,{a: 1, b:3}, "Hello");
set(a,{a: 3, b:1}, "World");
set(a,{a: 2, b:2}, "something else");
console.log(a)
First of all you need to understand that two object initialized with same values will never be equal to each other. Try running the following snippet.
Hence map creates two different elements with it.
var x = {a: 1, b:3};
var y = {a: 1, b:3};
var z = x;
console.log(x === y); // => false
console.log(x === z); // => true
Therefore, if you wish to group based on object as keys you will probably have to pass the objects as references as shown below:
let a = new Map();
let key = {a: 1, b:3};
a.set(key, "Hello");
a.set(key, "World");
console.log(a.get(key));
Alternatively instead of keeping track to references for each key, you can just stringify the object like so:
let a = new Map();
let key = JSON.stringify({a: 1, b:3});
a.set(key, "Hello");
a.set(key, "World");
console.log(a.get(key));

Javascript - Adding new label and data to existing array

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 !

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

JavaScript object property gets modified in a very interesting way

I have put together a small test, can someone explain why does JavaScript do the following?
Why will testArr inherit the modifications of newArray?
var TestClass = function() {
this.testArr = [10,11];
this.addToArray = function() {
var newArray = this.testArr;
newArray.push(12);
}
}
var testClass = new TestClass();
testClass.addToArray();
console.log(testClass.testArr); // will be [10, 11, 12]
Because they're the same array. Variables contain references to arrays. You're assigning that reference to a new variable, and now both variables point to the same array.
Here's a much simpler test which reproduces the behavior:
x = [1, 2] // the value of x is a reference to an array
y = x // the value of y is a reference to the same array
y.push(3) // modify the array pointed to by both variables
console.log(x) // [1, 2, 3]
If you want to create a new array, you need to clone the array.
With following statement
var newArray = this.testArr;
You will not copy the values from inside testArr. You will create a reference to this array. When you make an adjustment to a reference you will automatically change the referenced source too.
When you want to copy the values from testArr to another variable you can do this instead.
var newArray = this.testArr.slice();
This will copy the values from testArr inside newArray.

Categories