Returning variable name from array? - javascript

Is it possible to return a variable name from an array?
I have an array with 5 variables. Each variable is assigned a numeric value.
I am trying to find the highest value in the array and then alert its variable name, or possibly use that variable to do things with it.
var vara = 0; //resultA
var varb= 0; //resultB
var varc= 0; //resultC
var vard= 0; //resultD
var vare= 0; //resultE
function showResults() {
var buckets = [vara, varb, varc, vard, vare];
var largest = Math.max.apply(Math, buckets);
alert(largest);
}
The above code alerts the value of largest, but I want to find the corresponding variable, for instance vara instead of 3

No, it is not. If you want to associate some name with value, thats what dictionaries for.
var obj = {"name": 123, "name2": 234}
obj.name3 = 345; // assign 345 to name3
var valueOfName3 = obj.name3; // get name3
If you want to get the largest value in this object (by akonsu):
var largest = null;
var keyOfLargestVal = null;
for(var k in obj) { var v = obj[k];
if (largest === null || v > largest){
largest = v; keyOfLargestVal = k;
}
}

Related

Failing accessing array which is property of an object in Javascript

I'm trying to access array which is property of an object, but I can only access letters from property name.
var obj = {};
obj.line0=[0,0];
obj.line1=[0,50];
var pointsLenght = 8;
//things above are just test case sandbox representing small amount of real data
var createPoints = function(obj){
var i;
for(var x in obj){
if (obj.hasOwnProperty(x)) {
for (i=0;i<pointsLenght;i++){
if (i%2==0){
x[i]=i*50;
}
else {
x[i]=x[1];
}
console.log(i+" element of array "+x+" is equal "+x[i]);
}
}
}
return obj;
}
And this is what I get in console (Firefox 47.0):
0 element of array line0 is equal l
1 element of array line0 is equal i
2 element of array line0 is equal n
3 element of array line0 is equal e
4 element of array line0 is equal 0
5 element of array line0 is equal undefined
6 element of array line0 is equal undefined
7 element of array line0 is equal undefined
How to access array?
You are accessing the property name, that is a string. ("line0" and "line1")
For accessing the array belongs to that property name, Just write your code like,
var createPoints = function(obj){
var i;
for(var x in obj){
if (obj.hasOwnProperty(x)) {
for (i=0;i<pointsLenght;i++){
if (i%2==0){
obj[x][i]=i*50;
//obj[x] will give you the array belongs to the property x
}
else {
obj[x][i]= obj[x][1];
//obj[x] will give you the array belongs to the property x
}
console.log(i+" element of array "+x+" is equal "+ obj[x][i]);
}
}
}
return obj;
}
Operations need to be done obj[x].
Please Check with the code:
var obj = {};
obj.line0 = [0, 0];
obj.line1 = [0, 50];
var pointsLenght = 8;
//things above are just test case sandbox representing small amount of real data
var createPoints = function(obj) {
var i, elem;
for (var x in obj) {
if (obj.hasOwnProperty(x)) {
elem = obj[x];
for (i = 0; i < pointsLenght; i++) {
elem[i] = (i % 2 == 0) ? (i * 50) : elem[1];
console.log(i + " element of array " + elem + " is equal " + elem[i]);
}
}
}
return obj;
}
createPoints(obj);

How To Get Multiple Array Value Based On Another Array In Javascript

I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));

Add an existing var to a new object in JavaScript and loop through them

I find numerous guides on how to add variables to existing objects, but nowhere how to add an "existing" variable to an existing object.
I have a whole list with variables already defined in my script. e.g.: a, b, c, d.
and they all have their own values.
Now I want to call a function on all these variables and then show the variable-names and outcome in console.
Therefor I want to create an object out of them to loop through. How do I do this?
This is my workflow:
Values are created in various places in the script:
a = 1.333;
b = 1.64252345;
c = 2.980988;
I create the object and try to add the already existing variables (this is where I fail):
var abc = {};
abc.a;
abc.b;
abc.c;
I want to loop through the object, flooring all numbers, and printing the variable-name with the returned number:
var i;
for (i = 0; i < abc.length; ++i) {
var variablename = Object.keys(abc[i]);
var flooredvalue = floor(abc[i]);
var abc[i] = flooredvalue; // Save the floored value back to the variable.
console.log(variablename+": "+flooredvalue);
}
My desired output in console.log:
a = 1
b = 1
c = 2
Looping through the array of object keys will be a good idea.
a = 1.333;
b = 1.64252345;
c = 2.980988;
var abc = {};
abc.a = a;
abc.b = b;
abc.c = c;
var i;
var keys = Object.keys(abc);
console.log(abc['a'])
for (i = 0; i < keys.length; i++) {
var key = keys[i];
var flooredvalue = Math.floor( abc[key] );
abc[key] = flooredvalue;
window[key] = flooredvalue; //global variable change.
}
console.log(a);
console.log(b);
console.log(c);

Javascript - Get the associative array key value

I have an object with one key value as given below -
var a = {};
a.x = "randomvalue";
My requirement is to get access the value "randomvalue", but the catch is I dont know that the property name is "x".
Simplest way to get the value??
Try:
var v, i;
var a = {};
a.x = "randomvalue";
for (x in a) {
if a[x] === "randomvalue" {
v = x;
i = "randomvalue";
}
}
Then v contains the object key and i contains the object value (although you don't really need it).
Or, if you know the value index:
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Returning key/value pair in javascript

I am writing a javascript program, whhich requires to store the original value of array of numbers and the doubled values in a key/value pair. I am beginner in javascript. Here is the program:
var Num=[2,10,30,50,100];
var obj = {};
function my_arr(N)
{
original_num = N
return original_num;
}
function doubling(N_doubled)
{
doubled_number = my_arr(N_doubled);
return doubled_number * 2;
}
for(var i=0; i< Num.length; i++)
{
var original_value = my_arr(Num[i]);
console.log(original_value);
var doubled_value = doubling(Num[i]);
obj = {original_value : doubled_value};
console.log(obj);
}
The program reads the content of an array in a function, then, in another function, doubles the value.
My program produces the following output:
2
{ original_value: 4 }
10
{ original_value: 20 }
30
{ original_value: 60 }
50
{ original_value: 100 }
100
{ original_value: 200 }
The output which I am looking for is like this:
{2:4, 10:20,30:60,50:100, 100:200}
What's the mistake I am doing?
Thanks.
Your goal is to enrich the obj map with new properties in order to get {2:4, 10:20,30:60,50:100, 100:200}. But instead of doing that you're replacing the value of the obj variable with an object having only one property.
Change
obj = {original_value : doubled_value};
to
obj[original_value] = doubled_value;
And then, at the end of the loop, just log
console.log(obj);
Here's the complete loop code :
for(var i=0; i< Num.length; i++) {
var original_value = my_arr(Num[i]);
var doubled_value = doubling(original_value);
obj[original_value] = doubled_value;
}
console.log(obj);
You can't use an expression as a label in an Object literal, it doesn't get evaluated. Instead, switch to bracket notation.
var original_value = my_arr(Num[i]),
doubled_value = doubling(Num[i]);
obj = {}; // remove this line if you don't want object to be reset each iteration
obj[original_value] = doubled_value;
Or:
//Original array
var Num=[2,10,30,50,100];
//Object with original array keys with key double values
var obj = myFunc(Num);
//Print object
console.log(obj);
function myFunc(arr)
{
var obj = {};
for (var i in arr) obj[arr[i]] = arr[i] * 2;
return obj;
}

Categories

Resources