How to store value pairs in java script? - javascript

I need to store the below value pairs like in java script.
(1,1),(1,2),(1,3)(2,1),(2,2),(2,3)
1750 pairs like the above.
I tried using Map but map keys cannot contain duplicates.
Is there any other way i can store these value pairs in java script?
My function using map variable:
function repository()
{
var snakeRepo = new Map();
var xRepo,yRepo,count=0;
for (xRepo = 305;xRepo <=1085;xRepo=xRepo+15)
{
for (yRepo = 55;yRepo <=535;yRepo=yRepo+15)
{
snakeRepo.set(xRepo,yRepo);
//console.log(xRepo+","+yRepo);
count=count+1;
}
}
console.log(snakeRepo);
}

You can have an array inside of an array or objects inside of the array.
Array inside the array
var arrayInArray = [[1,2], [3,4]];
and you can access the values inside the array with:
//where 0 is the index of the values you want
arrayInArray[0]; //returns [1, 2];
Objects inside the array
var objectInArray = [{firstID: 1, secondID: 2},{firstID: 3, secondID: 4}];
and you casn access the values insde with:
where 0 is the index of the object you want
objectInArray[0]; //returns an object {firstID: 1, secondID: 2}
//alternatively, you can access your object's values by adding a dot
objectInArray[0].firstID; // returns 1
To save the date inside the array you can use
arrayInArray.push([1,2]);
objectInArray.push({id1: 1,id2: 2});

I don't know how you want to use it after, but you can store them as object individually ? Then push them in an array if you want :
var pair = {
value1 : 1,
value2 : 2
}
If values are generated in a for loop, it will be easy to use like this.

Related

Inserting items into array with bracket syntax doesnt affect length?

An array's length does not increase when adding items with bracket syntax. How do you update the length?
Example:
const a = [];
a['u123'] = 1;
a['u456'] = 2;
a.length; // returns 0
Arrays do not have keys, so your way of accessing them is also wrong. You could instead use push to add values to the array and the values will be index based, not key based.
const a = [];
a.push('u123');
a.push('u456');
console.log(a.length);
Or you could make your data an object instead, to have a key-value pair:
const a = {};
a['u123'] = 1;
a['u456'] = 2;
console.log(Object.keys(a).length)
That's because you are not adding items to the array instead you are inserting entries (key-value pairs) to your object.
You can check the length of the entries using the below syntax:
Object.keys(a).length // returns 2
If you want to add items to the array, use the below syntax:
a.push(1);
a.push('u123')
// ES6 syntax using spread operator
a = [...a, 2, 'u456']
a.length // returns 4
In order to get the length of an associative array you need to use the Object.keys length
Like so:
console.log(Object.keys(a).length);
If you want to update the length you need to use push. If you are using brackets you are adding a new property to an object (remember that an array is an object).
The length property return the number of elements in the array (not the properties).
var arrA = new Array();
var arrB = new Array();
arrA['propertyOne'] = 1; //add property 'propertyOne' with value 1 to the object arrA
arrA.push(2);
arrB.push(1);
arrB.push(2);
console.log(arrA); // [2, propertyOne: 1]
console.log(arrA[0]); // 2
console.log(arrA['propertyOne']); // 1
console.log(arrA.hasOwnProperty('propertyOne')); // true
console.log(arrA.length); // 1
console.log(arrB); // [1, 2]
console.log(arrB.length); // 2

How to check if array contains objects

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

Named objects and collection of them

not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Is there a way to return a variable's name from an array in Javascript?

I have an array that contains variables that could change position and I want to create a for loop that checks to see if a specific variable's length equals zero. I would rather not have to target the variable's position in the array, as it could change.
So, is there any way to target a variable in the array by the variable's name?
A dictionary is what you want.
var myDict = {x:"firstVariable", y:"second", z: ""}
//check length
for (key in myDict.keys()) {
if (len(myDict[key]) == 0) {
//Do something
}
}
Store your values with the variable names as the key, then just test the length of the value for each key.
Arrays normally store their data under number indexes like 0 1, 2, n so no. Store your variables in an Object using keys and access your vars using that keys with something like:
var data = {varName: var1, varName2: var2};
data['varName'] = //do your thing
You can access dynamically.
var personDetails = {name:"stanze", location: "earth" };
var p1="name";
var p2="location";
console.log(personDetails[p1]); //will print stanze
console.log(personDetails[p2]); //will print earth
Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly upon obj.
// Array-like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
print(Object.getOwnPropertyNames(obj).sort()); // prints '0,1,2'
var arr = ['a', 'b', 'c'];
print(Object.getOwnPropertyNames(arr).sort()); // prints '0,1,2,length'
// Printing property names and values using Array.forEach
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
print(val + ' -> ' + obj[val]);
});
Userful Article

Repeated index is not storing in associated array in Javascript

I am trying to store the array with the index and its value in associated array, But it is not storing repeated index with different value. When I alert this json value only unique value is displaying .Here is my code :
arr[1]="AAA";
arr[2]="BBB"
arr[3]="CCC"
arr[2]="DDD"
arr[2]="HHH"
var jsonString = JSON.stringify(arr);
alert(jsonString);
First, javascript has no concept of an associatively indexed array. You have either numerically indexed arrays or objects.
Second, if you try to write data to a given index (or property on an object) that is already defined, you WILL overwrite that value. This is common in any programming language.
It sounds like you simply need to rethink your data structure.
JavaScript does not allow repeated keys. When you write a value in a key that is already set, you are overwriting it and not creating a new key.
You may store multiple values in a key by using an inner list, like this:
arr[1]="AAA";
arr[2]=["BBB"];
arr[3]="CCC";
arr[2].push("DDD");
arr[2].push("HHH");
var jsonString = JSON.stringify(arr);
alert(jsonString);
If you want all your keys to behave like that, you can create a function to replicate this behavior:
function pushToKey(arr, key, value) {
var innerArr = arr[key];
if (innerArr) {
innerArr.push(value);
} else {
arr[key] = [value];
};
}
Then always use this function:
var myArr = [];
pushToKey(myArr, 1, "AAA");
pushToKey(myArr, 2, "BBB");
pushToKey(myArr, 3, "CCC");
pushToKey(myArr, 2, "DDD");
pushToKey(myArr, 2, "HHH");
This will make all values inside myArr to be stored as an array.

Categories

Resources