Avatar of tuchfeld
tuchfeld
 asked on

improve my javascript code syntax

Hi, following are 2 patterns of javascript code that I frequently use.
I suppose that there is a more "advanced" way to do it.

var found = false;
for (var i = 0; i < some_array.length; i++) {
    if (some_array[i].val == some_val) {
        found = true;
        break;
    }
}
if (found)
{
    // do something with some_array[i].
}

Open in new window


var found = false;
var key;
for (key in some_hashtable) {
    if (some_hashtable[key].val == some_val) {
        found = true;
        break;
    }
}
if (found)
{
    // do something with some_hashtable[key].
}

Open in new window

JavaScript

Avatar of undefined
Last Comment
Zvonko

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Michel Plungjan

I would expect the second to be


const found = hashtable[key] && hashtable[key] === some_val;

Open in new window

Julian Hansen

assuming you know the key - in this case he is "iterating" over the Object properties to see if any of them match a value.
Zvonko

Here the correction of Julian' version:


< script> 
var some_array = [1,2,42,33,5,7]; 
var some_val = 33; 
var some_val2 = 42; 
 
var element = some_array.find(function(item) { 
  return item === some_val; 
}); 
 
alert(element); 
 
var element2 = some_array.find(item => item === some_val2); 
alert(element2); 
< /script>

Open in new window



Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Zvonko

And my improvement for both arrays, hash and index array is this:


Create for the hash array a new array with reverse link from value to key.

Then you can lookup if value occures in your primary hash table and with what key.


The same for indexed array create a hash table for all values and their index numbers,


Both helper hash tables work only with unique values of course or yield tha last stored value key or value index.



Zvonko

PS. for numeric values you have to prefix the hash key value with at least one char. Othervise an index is assigned for nummeric hash keys.


Zvonko

And here my example for the indexed array:


< script> 
var some_array = [1,2,42,33,5,7]; 
var some_val = 33; 
var some_val2 = 42; 
 
var some_array_index = []; 
 
for(var i=0;i < some_array.length;i++){ 
	some_array_index["v_"+some_array[i]] = i; 
} 
 
if(some_array_index["v_"+some_val]) alert(some_array_index["v_"+some_val]); 
if(some_array_index["v_"+some_val2]) alert(some_array_index["v_"+some_val2]); 
< /script>

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Zvonko

The version for hash arrays looks preaty same  : )

tuchfeld

ASKER
Thank You all ! would you please write the code version for the hashtable problem.
Zvonko

here my reverse lookup table for hash array:


< script> 
var some_array = []; 
some_array["key_a"] = 33; 
some_array["key_b"] = 34; 
some_array["key_c"] = 42; 
 
var some_array_hash = []; 
for(var key in some_array){ 
	some_array_hash["v_"+some_array[key]] = key; 
} 
 
var some_val = 33; 
var some_val2 = 42; 
if(some_array_hash["v_"+some_val]) alert(some_array_hash["v_"+some_val]); 
if(some_array_hash["v_"+some_val2]) alert(some_array_hash["v_"+some_val2]); 
< /script>

Open in new window


This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
tuchfeld

ASKER
Zvonko thanks but, the hashtable keys format should not be assumed as pre-known as in your code.
Zvonko

It is not.

You lookup only the value in your array and get the key.

Zvonko

Here your example:

< script> 
var some_hashtable = []; 
some_hashtable["key_a"] = 33; 
some_hashtable["key_b"] = 34; 
some_hashtable["key_c"] = 42; 
 
var some_hashtable_hash = []; 
for(var key in some_hashtable){ 
	some_hashtable_hash["v_"+some_hashtable[key]] = key; 
} 
 
// end of preparation  
 
// now the lookup: 
var some_val = 33; 
var some_val2 = 42; 
if(some_hashtable_hash["v_"+some_val]) alert("element: "+some_val+"\nfound with this key: "+some_hashtable_hash["v_"+some_val]); 
if(some_hashtable_hash["v_"+some_val2]) alert("element: "+some_val2+"\nfound with this key: "+some_hashtable_hash["v_"+some_val2]); 
< /script>

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
tuchfeld

ASKER
this is e.g. for my question:
var some_hashtable = { a: { value: 1}, b: {value: 2}};
I'm looking for the hashtable item that has a specific value.
Zvonko

Here my version:


< script> 
var some_hashtable = { a: { value: 111}, b: {value: 222}}; 
 
var some_hashtable_lookup = []; 
for(var key in some_hashtable){ 
	some_hashtable_lookup["v_"+some_hashtable[key].value] = key; 
} 
 
// end of preparation  
 
// now the lookup: 
var some_val1 = 111; 
var some_val2 = 222; 
var some_val3 = 333; 
if(some_hashtable_lookup["v_"+some_val1]){alert("element found: "+some_val1+"\nkey is: "+some_hashtable_lookup["v_"+some_val1])} else alert("not found: "+some_val1); 
if(some_hashtable_lookup["v_"+some_val2]){alert("element found: "+some_val2+"\nkey is: "+some_hashtable_lookup["v_"+some_val2])} else alert("not found: "+some_val2); 
if(some_hashtable_lookup["v_"+some_val3]){alert("element found: "+some_val3+"\nkey is: "+some_hashtable_lookup["v_"+some_val3])} else alert("not found: "+some_val3); 
< /script>

Open in new window

tuchfeld

ASKER
I would prefere a solution without lookup. a short and clean solution. I suppose, as Julian said, it should be done using a Map() or Set()
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Zvonko

Map() das NOT work for reverse lookup of values in the Map.


Take my reverse lookup constructor  ;-)



Zvonko

OK, then check this version without lookup table:


< script> 
Object.prototype.mySearch = function(val){for(var key in this){if(this[key].value === val)return key}return null} 
 
var some_hashtable = {  
	a: { value: 111, name: "first"},  
	b: {value: 222, name: "second"},  
	c: {value: 333, name: "third"} 
}; 
 
var myKey = some_hashtable.mySearch(222); 
if(myKey) alert(some_hashtable[myKey].name); 
 
 
< /script>

Open in new window

Zvonko

@ tuchfeld: does it work for you?

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

@Zvonko
Here the correction of Julian' version:
What correction are you referring to?

My code is predicated on an array of objects as specified in the opening question?
tuchfeld

ASKER
@Zvonko, I'm looking for a "modern" one-line statements as Julian solved it for the array (the first answer).
Zvonko

Sorry, please ask Expert Julian.

Your help has saved me hundreds of hours of internet surfing.
fblack61
tuchfeld

ASKER
ok, I think, this is what I was looking for the hashtable part:
var key = Object.keys(some_hashtable).find(key => some_hashtable[key].val === some_val);

Open in new window

tuchfeld

ASKER
Thank you all for the replies and care!
Zvonko

@ tuchfeld: very good : )


Correct your typo to this and it works:

var key = Object.keys(some_hashtable).find(key => some_hashtable[key].value === some_val);


⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
tuchfeld

ASKER
@Zvonko, so let's write the full answer (tested):

var some_array = [
  { name: "a", value: 1 },
  { name: "b", value: 2 }
];
var some_value = 2;
var obj = some_array.find(item => item.value === some_value);
alert(obj.name);
//
var some_hashtable = { a: { value: 1 }, b: { value: 2 } };
var key = Object.keys(some_hashtable).find(
  key => some_hashtable[key].value === some_value
);
alert(key);

Open in new window

Zvonko

Thank you tuchfeld for the wrap up solution.


Zvonko

I bag for pardon from my side to Expert Julian.


I have changed Julian's correct solution based on first Question example. 


Julian has the correct Array elements property .val from the first example which I have removed.


Sorry for confusion.

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck