How to dynamically create associative array - javascript

I am currently doing this but it isn't working:
var tempArray=new Array();
var number = 15;
tempArray[number]='blabla';
for (var key in tempArray) {
alert(tempArray[key]);
}
the output that I get is:
in_array function (element) { var retur = false; for (var values in this) { if (this[values] == element) { retur = true; break; } } return retur; }
What am I doing wrong?

In JavaScript we use Objects.
var obj = {};
obj["15"] = "blabla";
obj.fifteen = "blablah";
for(var i in obj) {
alert(obj[i]);
}

Related

I want to implement the hashtable in javascript but it has an exception

function HashTable(){
var size = 0;
var entry = new Object();
this.add = function(key,value){
if(!containsKey(key)){
size++;
}
entry[key] = value;
}
this.getValue = function(key){
return containsKey(key)?entry[key]:null;
}
this.remove = function(key){
if (containsKey(key) && delete entry[key]) {
size--;
}
}
this.containsKey = function(key){
return (key in entry);
}
this.containsValue = function(value){
for(var prop in entry){
if(entry[prop] == value){
return true;
}
}
return false;
}
//get all values
this.getValues = function(){
var values = new Array();
for(var prop in entry){
values.push(entry[prop]);
}
return values;
}
//get all keys
this.getKeys = function(){
var keys = new Array();
for(var prop in entry){
values.push(prop);
}
return keys;
}
this.getSize = function(){
return size;
}
this.clear = function(){
size = 0;
entry = new Object;//???????????????????
}
}
var hashtest = new HashTable();
hashtest.add('name','LiMing');
I want to implement the hashtable in javascript but when I test it ,there is an exception like this:
Uncaught ReferenceError: containsKey is not defined
at HashTable.add (:8:3)
at :64:10
The problem you have is an issue of scope. The javascript interpreter does not know you mean the containsKey from the HashTable class.
When calling functions within the class scope be sure to reference them with "this". So containsKey should be referenced as this.containsKey(key). That way the interpreter knows you are referring to the class' scope and not the local scope.
You should also do this for the variables with class scope. So when you do size++ you should actually write this.size++. Same for entry. If you do not add "this", it will assume it is a local function or variable defined within that function itself.
So you should rewrite your add() function as
this.add = function(key,value){
if(!this.containsKey(key)){
this.size++;
}
this.entry[key] = value;
}
Why are you manually keeping track of the size anyway? You can simply define "entry" as an array and use this.entry.size
Considering the more specific case of the hashmap, I would advice you to simply create two arrays within the object, one for the keys and one for the values, this will drastically simplify the problem for you because then you can simply use the builtin Javascript array functions. Both arrays will have a numerical index but the key and the value will both always have the same index so you can easily math them up. The result would be like this:
function HashTable() {
this.keys = new Array();
this.values = new Array();
this.add = function(key, value) {
if (this.containsKey(key)) {
var index = this.keys.indexOf(key);
this.values[index] = value;
} else {
this.keys.push(key);
this.values.push(value);
}
}
this.containsKey = function(key) {
return this.keys.includes(key);
}
this.containsValue = function(value) {
return this.values.includes(value);
}
this.get = function(key) {
var index = this.keys.indexOf(key);
return this.values[index];
}
this.remove = function(key) {
if (this.containsKey(key)) {
var index = this.keys.indexOf(key);
this.keys.splice(index, 1);
this.values.splice(index, 1);
}
}
this.size = function() {
return this.keys.length;
}
this.clear = function() {
this.keys = new Array();
this.values = new Array();
}
}
// Create hashtable
var hashTable = new HashTable();
// Add some test data
hashTable.add('name', 'LiMing');
hashTable.add('location', 'At home');
hashTable.add('eyes', 'blue');
// Updates the value, doesn't add it
hashTable.add('eyes', 'brown');
console.log(hashTable.get("eyes"));
// Get the size
console.log(hashTable.size());
// Check if a value or key is in the hashtable
console.log(hashTable.containsValue("test")); // False
console.log(hashTable.containsValue("LiMing")); // True
console.log(hashTable.containsKey("name")); // True
console.log(hashTable.containsKey("age")); // False
// Get all the keys and values
console.log(hashTable.keys);
console.log(hashTable.values);
// Remove an item
hashTable.remove('eyes');
console.log(hashTable.keys);
console.log(hashTable.values);
// Clear hashtable
hashTable.clear();
console.log(hashTable.keys);
console.log(hashTable.values);
Use this.containsKey instead, as containsKey is a 'member' method inside the object created by HashTable, you have to reference it with this.
function HashTable(){
var size = 0;
var entry = new Object();
this.containsValue = function(value){
for(var prop in entry){
if(entry[prop] == value){
return true;
}
}
return false;
}
this.add = function(key,value){
if(!this.containsKey(key)){
size++;
}
entry[key] = value;
}
this.getValue = function(key){
return this.containsKey(key)?entry[key]:null;
}
this.remove = function(key){
if (this.containsKey(key) && delete entry[key]) {
size--;
}
}
this.containsKey = function(key){
return (key in entry);
}
//get all values
this.getValues = function(){
var values = new Array();
for(var prop in entry){
values.push(entry[prop]);
}
return values;
}
//get all keys
this.getKeys = function(){
var keys = new Array();
for(var prop in entry){
values.push(prop);
}
return keys;
}
this.getSize = function(){
return size;
}
this.clear = function(){
size = 0;
entry = new Object;//???????????????????
}
}
var hashtest = new HashTable(); hashtest.add('name','LiMing');
console.log(hashtest.getValues())
There's a better way to organize your code using ES6:
class HashTable {
constructor() {
this.size = 0;
this.entry = new Object();
}
containsValue(value) {
for(var prop in entry){
if(this.entry[prop] == value){
return true;
}
}
return false;
}
add(key,value) {
if(!this.containsKey(key)){
this.size++;
}
this.entry[key] = value;
}
getValue(key) {
return this.containsKey(key) ? this.entry[key] : null;
}
remove(key) {
if (this.containsKey(key) && delete this.entry[key]) {
size--;
}
}
containsKey(key) {
return (key in this.entry);
}
//get all values
getValues() {
var values = new Array();
for(var prop in this.entry){
values.push(this.entry[prop]);
}
return values;
}
//get all keys
getKeys() {
var keys = new Array();
for(var prop in this.entry){
values.push(prop);
}
return keys;
}
getSize() {
return this.size;
}
clear() {
this.size = 0;
this.entry = new Object();//???????????????????
}
}
var hashtest = new HashTable(); hashtest.add('name','LiMing');
console.log(hashtest.getValues())

Push to an array in a nested loop is repeating the last value

I am trying to push elements to an array in a nested loop, but only the last item is getting repeated in the final array, where am I going wrong, very new to javascript asynchronous concept.Below is the function in which I push the items to an array.
$scope.showBeList = function(feed) {
if (feed[srcServ.KEY_CONTENT_TEXT]) {
var content = JSON.parse(feed[srcServ.KEY_CONTENT_TEXT])
if (content) {
$scope.beList = {};
for (var key in content) {
var decorationVal;
//reading value from a lokijs collection
var decoration = dataServ[srcServ.CONST_COLLECTION_DECORATION].find({
'name': key
});
if (decoration && decoration.length) {
decorationVal = decoration[0];
if (decorationVal != null) {
var tempObj = JSON.parse(decorationVal.value);
if (tempObj) {
var header = tempObj[key][key + '_HEADER'];
if (header) {
var counter = content[key].length;
var tempItems = [];
for (var j = 0; j < content[key].length; j++) {
(function(j) {
var obj = {};
obj[srcServ.KEY_MAIN_HEADER] = tempObj[key][srcServ.KEY_DESC];
obj[srcServ.KEY_SUB_HEADER] = header[srcServ.KEY_DESC];
obj.id = j;
var itemVal = content[key][j][key + '_HEADER'];
var details = [];
var notes = [];
for (var item in itemVal) {
var val = null;
var found = false;
for (var i = 0; i < header.field.length; i++) {
if (header.field[i].name == item) {
val = header.field[i];
found = true;
break;
}
}
if (found && val != null) {
val[srcServ.KEY_DESC_VALUE] = itemVal[item];
details.push(val);
}
}
obj.details = details;
counter--;
if (counter == 0) {
$scope.showMoreDetails = true;
$scope.beList.beItems = tempItems;
console.log(JSON.stringify($scope.beList));
}
tempItems.push(obj)
})(j);
// $scope.beList.beItems.push(obj);
}
}
}
}
}
}
}
}
}

JavaScript - How to cross-compare an array to itself

I have an array like this:
var myObjArray = [{city: 'milwaukee', state: 'wi'},
{city:'madison', state: 'wi'},
{city:'greenbay', state: 'wi'},
{city:'madison', state: 'wi'}];
How would I compare the array against itself to find duplicates.
(Note: I need to keep the duplicates, so maybe I could add a property to the object as a flag).
How about something like:
var bucket = {};
for(var i=0;i<array.length;i++) {
var item = array[i];
var hash = JSON.stringify(item); //or some a hashing algorithm...
var prev = bucket[hash];
if(prev) {
prev.duplicate = item.duplicate = true;
} else {
bucket[hash] = item
}
}
Or same without dependending upon JSON.stringify:
var markDuplicates = function(array, hashFunc) {
var bucket = {};
for(var i=0;i<array.length;i++) {
var item = array[i];
var hash = hashFunc(item);
var prev = bucket[hash];
if(prev) {
prev.duplicate = item.duplicate = true;
} else {
bucket[hash] = item
}
}
return array;
};
markDuplicates(yourArray, function(item) { return item.city + item.state; });

Error extract keyword from Google search in Javascript?

I have a sample code:
function getKeyword() {
var instance = this;
var googlePattern = /(www\.google\..*)/;
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
return result;
};
this.googleKeywords = function(params){
var query = params["q"];
var pattern = /"(.*?)"|(\w+)/g;
return decodeURIComponent(query).replace(/\+/g, " ").match(pattern);
};
this.parseReferrer = function(){
var result = [];
var pathAndParams = document.referrer.split("?");
if(pathAndParams.length == 2) {
var path = pathAndParams[0];
var params = this.params(pathAndParams[1]);
if(path.search(googlePattern) > 0) {
result = this.googleKeywords(params);
}
}
return result;
};
return this.parseReferrer();
}
And then:
<script type="text/javascript">
if (document.referrer && document.referrer != "") {
if (document.referrer.search(/google\.*/i) != -1){
var keyword = getKeyword();
alert(keyword);
} else {
alert('Not search from google');
}
} else {
alert('Not referrer');
}
</script>
Ex: when i search with keyword is "iphone 5", result not show alert("iphone 5") ? How to fix it ?
The JavaScript for in construct loops over more than just the entries in the array. If you want to use for in you need to make sure that you're only processing the actual parameters. This is easiest accomplished by checking for hasOwnProperty:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
if (params.hasOwnProperty(p))
{
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
}
return result;
};
Alternatively you can use a regular for loop over the array:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var i=0; i < params.length; i++) {
var kv = params[i].split("=");
result[kv[0]] = kv[1];
}
return result;
};

JavaScript: Having trouble returning custom object information

I've made some new objects with object methods and I'm having trouble returning the information.
I intend for allPages to be a 2d array:
var allPages = [[]];
function textbox(type)
{
this.type=type;
this.getInfo = function () { return ( this.type ); };
}
function addTextbox(dropdown)
{
var myindex = dropdown.selectedIndex;
var SelValue = dropdown.options[myindex].value;
if(SelValue == "String")
{
var tb = new textbox("string");
allPages[allPages.length-1].push(tb);
var string = "";
for (i = 0;i < allPages.length;i++)
{
for(j = 0;j < allPages[i].length;j++)
{
string = string + allPages[i][j].getInfo;
}
}
<!-- Problem here: prints "function () { return this.type; }"-->
document.write(string);
}
}
}
You are not calling the function, you are referencing it
allPages[i][j].getInfo;
should be
allPages[i][j].getInfo();
3 lines above where you state the problems exists, it should be:
string = string + allPages[i][j].getInfo(); // mind the () at the end.

Categories