Storing values in array and retrieving from array when checkbox is checked - javascript

I am storing some values in array like this.
var test = [];
I am pushing the values to this array as test.push(sample);
I have some logic for calculating this value
var sample= (a/b.length)*100;
When I click on a button, the above logic for calculating value of sample is done and once I got the value of sample I am pushing it to test[] array. Now I want to retrieve all the values from the test[] array whenever I check the checkbox. I am able to do all this but I am facing a problem here. only the last pushed value is saving. but I want to save all the values that are being pushed. can anyone please help me in solving this issue.
Quick response is needed and appreciated
Regards
Hema

You need to use 2 dimensional array for this.
Use
var test= new Array();
then assign value test['someKey']=sample;
or test.push(sample); . you can retrieve array value like alert(test[0]) or by iterating array with $.each(test,function(index,value){alert(value)});

What you want to do is create an Array which would function as a list of value sets.
You would then be able to push all the changes into an array, and put it in the list.
for instance:
var mainList = new Array();
var changeListA = new Array();
var changeListB = new Array();
// do some stuff on change list **a** .. push(something)
changeListA .push(something);
changeListA .push(something);
changeListA .push(something);
// do some stuff on change list **b** .. push(something)
changeListB .push(changeListB);
mainList.push(changeListA);

Your question is not perfectly clear to me, however I can at least provide a small jsFiddle that proves to you that (how) array.push works.
Other answers indicate that what you want is either a two dimensional array, or a "hashmap" or "associative array" where the array values are stored using a key name. The code here can be used in the fiddle to achieve either or...
http://jsfiddle.net/xN3uL/1/
// First if you need 2 dimensional arrays:
myArray.push( ["Orange", "Apple"] );
myArray.push( ["Mango", "Pineapple"] );
// Secondly, if you need hashmap or associative array:
var myObj = {};
myObj['key'] = 'value';
alert(myObject.key);

Related

JS: Iterate over an array of objects to update object

I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.
arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]
for (var list_obj of arr_lists) {
list_obj = list_obj.join().split(',').filter(onlyUnique);
list_obj.sort();
Logger.log(list_obj);
}
The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.
I've tried assigning the filtered array to a new array... nope.
I know that I could add a thousand lines of code to achieve the results, but that seems silly.
I suspect it's something obvious.
You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.
Live Demo :
const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];
arr_lists.forEach((arr, index) => {
arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})
console.log(arr_lists);

Use index to subset an array in Apps Script

I am new to apps script (was a Matlab user before). I am trying to subset an array "names" based on the value of another array "index". Both arrays have the same length:
names = [["name1"], ["name2"], ["name3"], ["name4"], ["name5"],["name6"],["name7"],["name8"],["name9"],["name10"]];
index = [0,0,1,0,1,0,0,0,0,1];
I want to subset array "names" to just pick up the names where the "index" has a value of 1. I wrote:
var subsetNames = names[index];
in the hope to get "subsetNames" to equal to:
[["name3"],["name5"],["name10"]]
The code runs but "subsetNames" remains undefined. How can I modify the code to achieve the subsetting? thanks.
How about this? I think that there are several answers for your situation. So please think of this as one of them.
Sample script:
var names = [["name1"], ["name2"], ["name3"], ["name4"], ["name5"], ["name6"], ["name7"], ["name8"], ["name9"], ["name10"]];
var index = [0,0,1,0,1,0,0,0,0,1];
var subsetNames = names.filter(function(e, i) {return index[i] == 1}); // [["name3"],["name5"],["name10"]]
Note:
This script supposes that the array lengths of both names and index are the same.
Reference:
filter()

Get a key from an array inside an array in javascript

var Game1 = ["name", "image", "genre"]
var Game2 = ["name2", "image2", "genre2"]
var Game3 = ["name3", "image3", "genre3"]
var games = [Game1, Game2, Game3]
I want to store some arrays inside an other array, as shown above, and I want to be able to show all of the names of the arrays. So here, I would like to get Game1[0], Game2[0] and Game3[0], but I want to get them from the games array.
How would I go about doing this?
I was thinking of using a for loop over games, but I'm not sure how to get the 0th element from the arrays inside the games array.
I'm quite new to javascript, which is why I could not figure this out.
You can access like below.
games[0][0] - will gives you the Game1[0] value
games[1][0] - will gives you the Game2[0] value
games[2][0] - will gives you the Game3[0] value
DEMO

Checking for existing array in array before pushing

I missing something when trying to push to an array while preventing duplicates.
I keep figuring out code that will push every occurence of an employee to the new employees array but I cannot figure out how to only push an unique list.
My final array is a 2d array so that can be setValues() back into a column in the Google sheet.
function queryEmployees(){
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var lRow = sh.getLastRow();
var data = sh.getRange(1,1,lRow,2).getValues();
var employees = [];
for(i=0;i<data.length;i++){
if(data[i][0]==='Team member evaluated'){
if(employees.indexOf([data[i][1]])===-1){
employees.push([data[i][1]]);
}
}
}
Logger.log(employees);
Logger.log(employees.length);
SpreadsheetApp.getActiveSpreadsheet().getSheets()[1]
.getRange(1,1,employees.length,1).setValues(employees);
}
IndexOf does not work with objects in arrays without your rewriting the function or writing your own. It works fine with strings, though. So a simple fix is to create a parallel array of strings, which allows us to keep your code almost intact. Thus, add,
var employeesIndex=[];
after your
var employees=[]
change the condition on your inner "if" clause to
(employeesIndex.indexOf(data[i][1])===-1)
and within that if block add a line to update the index
employeesIndex.push(data[i][1]);
That way the index tracks duplicates for you while your employees array contains arrays like you need.

jQuery loop to put together multiple arrays - Mapbox map.setFilter()

Mapbox's new GL API is proving difficult to use. I'm wondering if I can build an array with this strange format through jQuery's each function.
I'm creating a form with checkboxes for categories that would filter the markers shown on the map. I'm using a $.each() loop to grab the checked inputs, get their ID, and throw it in the middle of each array. One checked input is one array.
Basically, I need the array to be put together as such:
map.setFilter('markers', ["any",
['in',c1,true],
['in',c2,true], // these 3 arrays
['in',c3,true]
] );
But obviously, I need this done dynamically on check. Here's the incomplete jQuery I'd like to use:
jQuery('input.checkbox-child').change(function(){
args = new Array();
jQuery('input.checkbox:checked').each(function(){
id = jQuery(this).attr('id');
filter = ['in',id,true];
// ???
});
map.setFilter('markers', ["any", args] );
});
Not sure how I would join the filter variables together to form a comma-separated list of arrays, similar to ['in',id,true],['in',id,true],['in',id,true]... for use in the setFilter function.
I think this should work for what you want
var args = [];
jQuery('input.checkbox-child').change(function(){
jQuery('input.checkbox:checked').each(function(){
var id = jQuery(this).attr('id');
var filter = ['in',id,true];
args.push(filter);
});
map.setFilter('markers', ["any"].concat(args));
});

Categories