Get array from dynamic variable - javascript

I'm sure this is really simple, I just can't work out how to do it.
I want to dynamically make an array from one variable equal to another:
var pageID = document.getElementsByClassName('page_example')[0].id;
Let's say this returned an id of page_1
var page_1 = ['value1','value2','value3'];
var page_2 = ['value4','value5','value6'];
var page_3 = ['value7','value8','value9'];
var page_array = (then have the associated pageID's array here)
So in this example,
page_array would equal ['value1','value2','value3']

Instead of storing the array in separate variables, store them in an object with the ids as the key:
var pages = {
page_1: ['value1','value2','value3'],
page_2: ['value4','value5','value6'],
page_3: ['value7','value8','value9']
}
You can access the arrays as though the object was an assosiative array:
var pageID = "page_1";
var pageArray = pages[pageID];

Depending on what you would like to achieve, you can one of two or three methods.
What I consider the easiest method is an if/else statement:
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(0);
} else if...
Another method you can use, again depending on what your ultimate goal is, would be a for loop:
for (var i = 0; i < numOfDesiredLoops; i++) {
page_array = page_1.slice(0, i);
}
Or you could use a combination of both:
for (var i = 0; i < numOfDesiredLoops; i++) {
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(1);
} else if...
}
With more information on why you need this variable to change, I can give you a better answer.
edit: keep in mind the arguments of .slice() can be whatever you want.

Related

Advice on the best way to collect values in an array

I need to save all the color values ​​of the elements in the pages of my site and put them in a database. I thought I'd do it this way:
First thing I'm going to pick up the rgb values ​​of each element so
$("*").each(function(e){
createColorArray($(this).css('backgroundColor'));
});
then in the function createColorArray store into an array all the values ​​that are passed
function createColorArray(rgbColor)
{
//Create rgb array
}
and finally remove duplicate items from my array
function removeDoupe(ar) {
var temp = {};
for (var i = 0; i < ar.length; i++)
temp[ar[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
now my question is,
how recommended to create the array? directly inside the $ ("*") or in a dedicated function as I'm thinking? also i need than once removed duplicates in the new array "clean" as well as the rgb value I would have also given the number of times that value was in the original.
Some example code?
As I mentioned in the comments, why not check for duplicates earlier? A simple example:
var colors = [];
$('*').each(function(i, el){
var $element = $(el),
color = $element.css('background-color');
if(!~$.inArray(color, colors))
colors.push(color);
});
console.log(colors);
http://jsfiddle.net/sL9oeywk/
The best way to do this is to do it all while you are working on it. Heres a way you could potentially do it:
var colors = new Array();
var tempColors = {};
$(".colors").each(function(){
var c = $(this).val();
// check if the color exists without looping
if(typeof tempColors[c] == "undefined"){
// if it doesn't, add it to both variables.
tempColors[c] = true;
colors.push(c);
}
});
This will result in two variables: one is an object that you don't have to loop through to find out if you defined it before, one is a colors array that you push to using standard javascript.
You shouldn't make it a dedicated function if you are not reusing it, but you could make it an object like this:
var colors = function(){
var self = this;
self.array = new Array();
// this is a dedicated check function so we don't need separate variables.
// returns true if the color exists, false otherwise
self.check = function(color){
for(var i =0; i < self.array.length; i++){
if(self.array[i] === color) return true;
}
return false;
}
self.add = function(color){
// use the check function, if it returns false, the color does not exist yet.
if(!self.check(color)){
self.array.push(c);
}
}
}
You can then instantiate a colorlist using var colorlist = new colors(); and add colors using colorlist.add("dd0300"). Accessing the array can be done by requesting colorlist.array.

Make use of a global array

I want to use the values that I get from a request, but the response object is a local variable (an array). Therefore I create this global array:
<script type="text/javascript">
var response = [];
as you see, right under the script opening tag, so it is global. Then in the function where I have the response I added this:
jsonResponse.forEach(function(element){
response[element.size] = element.id;
});
And then added this, with the purpose to make use of the values that I've got in my global var from the response object:
getIdOfProductBySize: function() {
var selectedIndex = document.getElementById('dropdown_options').value;
for (var key in response) {
if (key != selectedIndex) {
continue;
} else {
return response[key];
}
}
}
Doesn't work, so I started going step by step (of the order I add the new things) and I noticed that the script breaks after the 2nd thing that I add (where the forEach is).
Maybe I am not declaring the global variable correctly, or maybe I cannot access it this way, or maybe I don't assign the values to it in the correct way, I don't know, so I am asking if someone can give me a hint how to make use of all this working together?
Try this:
var response = {key1: value1};
var i = 2;
jsonResponse.forEach(function(entry) {
console.log(entry);
response["key"+i] = entry.id;
i++;
});
var index;
for (index = 0; index < response.length; ++index)
{
console.log(response[index]);
if(response["key"+index] !== selectedIndex)
continue;
else
return response["key"+index];
}
Looks like you're going to need a two dimensional array.
Looks to me like your "key" value is undefined.
before:
for (var key in response) {
try:
var k=response.whatever;
If that makes sense?
response[element.id] = element.size;
Try this one, i believe element.size returns the actual size of an element and is not what you want to use as index in an array.

How do you write to a span using jQuery?

I'm trying to populate a <span></span> element on the page load with jQuery.
At the moment the value that gets populated into the span is just an integer count.
Here I have named my span userCount:
Users<span id = "userCount"></span>
I am trying to write the value of the span with no success.
$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {
var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;
var countUsers;
for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();
});
});
You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.
$('#userCount').html(countUsers);
Note also that
you don't need to convert your integer to a string manually.
if you don't break from the loop, countUsers will always be table.length-1.
you have a typo : dataSet instead of dataset. Javascript is case sensitive.
you don't need to parse the result of the request
you don't need to pass empty data : jQuery.post checks the type of the provided parameters
So, this is probably more what you need, supposing you do other things in the loop :
$.post("Dashboard/UsersGet", function (dataset) {
var table = dataset.Table;
var countUsers = table.length; // -1 ?
// for now, the following loop is useless
for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
var array = table[i];
if (array.Active == 1) { // I hope array isn't an array...
var name = array.Name; // why ? This serves to nothing
}
}
$('#userCount').html(countUsers);
});
Use .html()!
Users<span id = "userCount"></span>
Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html().
$("#userCount").html(5000);
Or in your case:
$("#userCount").html(countUsers.toString());
Change:
userCount.innerHTML = countUsers.toString();
to:
$("#userCount").html(countUsers.toString());
Instead of:
userCount.innerHTML = countUsers.toString();
use:
$('#userCount').html(countUsers.toString());
You could use
$('#userCount').text(countUsers);
to write data to span
The call back argument should be dataSet rather than dataset?

fastest way to loop through an array

I want to return an array when one of the elements matches an item within an array.
Is the below code the fastest way to loop through an array when a value matches in a javascript array of arrays?
Note : Welcome any suggestions to modify the variable relatedVideosArray to make it a different data structure for better performance.
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
function getRelatedVideos(videoClicked){
var tempStoreArray = [];
var getCurrentId = videoClicked;
var relVideoslen = relatedVideosArray.length;
for(var i in relatedVideosArray) {
tempStoreArray = relatedVideosArray[i];
for(var j in tempStoreArray){
if(tempStoreArray[j] == getCurrentId){
return relatedVideosArray[i];
}
}
}
}
Update: I initially thought of making a key of video ids and values as all the related ids, but I want to display the key as well as all the related ids if any of the ids within the value array are clicked. Hope this helps to explain the constraint I have.
Modern day browsers support Array indexOf.
For the people saying the array indexOf is slower, basic tests on speed.
var values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
console.time("for");
for(var i=0;i<1000;i++){
for(var j=0;j<=values.length;j++){
if(values[j]===20) break;
}
}
console.timeEnd("for");
console.time("reverse for");
for(i=0;i<1000;i++){
for(var j=values.length-1;j>=0;j--){
if(values[j]===1) break;
}
}
console.timeEnd("reverse for");
console.time("while");
for(i=0;i<1000;i++){
var j=0;
while (j<values.length){
if(values[j]===20) break;
j++;
}
}
console.timeEnd("while");
console.time("reverse while");
for(i=0;i<1000;i++){
var j=values.length-1;
while (j>=0){
if(values[j]===1) break;
j--;
}
}
console.timeEnd("reverse while");
console.time("indexOf");
for(var i=0;i<1000;i++){
var x = values.indexOf(20);
}
console.timeEnd("indexOf");
console.time("toString reg exp");
for(var i=0;i<1000;i++){
var x = (/(,|^)20(,|$)/).test(values.toString);
}
console.timeEnd("toString reg exp");
Two possible solutions:
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
//var getCurrentId = "1019385098001";
var getCurrentId = "1040885813001";
console.time("indexOf");
var tempStoreArray = [];
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(subArr.indexOf(getCurrentId)!==-1){
tempStoreArray.push(subArr);
}
}
console.timeEnd("indexOf");
console.log(tempStoreArray);
console.time("toString reg exp");
var tempStoreArray = [];
var re = new RegExp("(,|^)" + getCurrentId + "(,|$)");
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(re.test(subArr.toString())){
tempStoreArray.push(subArr);
}
}
console.timeEnd("toString reg exp");
console.log(tempStoreArray);
I believe so if you keep your current structure. Unless you have a way of 'flattening' the array first, so that rather than being nested, there is simply one array with all the values. If this is out of your control or impractical, then you have no other choice than to iterate over every element and its elements.
Otherwise, would you be able to add the values to a map? The current video id would be the key, and the value would be the list of related videos.
If you have control over the data structure then I highly recommend changing it to something more amenable to the type of searches you are performing. First thing that comes to mind is an array of associative arrays. Each of your video arrays would be keyed with the video id ( set the value to anything you want ). That would make your search O(n), where n = the total number of video lists you have.
I'll post some code for this when I get in front of the computer.

A good way to associate a counter to each member of an array in Javascript?

I have an array of strings in Javascript like `var elements = ["string1", "string2"]; The array is created dynamically so it could contain any number of strings. I want to associate a counter to each element of the array. The counter will increment or decrement during the webpage's life.
I was going to try element["string1"].counter = 1; but it didn't work.
What's a good way to implement this?
If you had an array var elements = ["string1", "string2"], you could not access an element with elements["string1"], you are using the value not the index. elements[0] is the correct form of access to the element, using the numerical key.
Even then, strings are special types of object and do not appear to take additional parameters readily, at least not when I tested a moment ago. Which is odd.
You could quickly knock the array in to a set of objects with separate text and counter components.
var elements = ["string1", "string2"];
var elementsWithCounter = [];
for(var index = 0; index < elements.length; index++) {
elementsWithCounter[i] = { text: elements[index], counter: 1 };
}
You could also create a "hash table" using a plain object such as:
var counter = {};
for(var i = elements.length; i--; ) {
counter[elements[i]] = 1;
}
Then you could increment the counter with:
counter['string1'] += 1;
or
counter[elements[0]] += 1;
This might help you.
elementArray = ["string1", "string2"]
function setCounter(str, val) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) elementArray[i].counter = val;
}
}
function getCounter(str) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) return elementArray[i].counter;
}
}
setCounter("string1", 5);
getCounter("string1");
Alternatively just access elementArray[index].counter
Javascript primitives/built in objects can't have properties/attributes added to their prototype (i.e. String.prototype.counter = -1 doesn't work correctly). Image, String, Date, Array all can't have properties added.
Maybe instead of a string you should make it an object, similar to what Orbling has posted.

Categories