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

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));
});

Related

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.

knockout js, add new item to an array

So this follows on from my previous question:
knockout js, add additional elements to an array
Basically I have an app where a user fills in certain data, clicks next and this is added to an array. However, what I'd like to do is add some items into the array before the user even begins using the app (these items I get from a database). The idea being that at the start they can view each item in the array and then choose and an item and edit this item. I've got a feeling I'm missing something blindingly obvious but I cannot seem to figure it out
Knockout observable arrays have equivalent functions to native JavaScript arrays. See: http://knockoutjs.com/documentation/observableArrays.html
So you need just to use arr.pop(item) or arr.push(item).
In case you need to replace all items and want to avoid multiple events to raise, use observableArray.valueWillMutate() and valueHasMutated() functions. See sample where I do swap the entire array:
ko.observableArray.fn.replaceWith = function (valuesToPush) {
// NOTE: base on - ko.observableArray.fn.pushAll
var underlyingArray = this();
var oldItemcount = underlyingArray.length;
this.valueWillMutate();
// adding new items to obs. array
ko.utils.arrayPushAll(underlyingArray, valuesToPush);
// removing old items (using KO observablearray fnc.)
if (oldItemcount > 0)
this.removeAll(underlyingArray.slice(0, oldItemcount));
this.valueHasMutated();
return this; //optional
};

How to make an array from JSON?

Couldn't think of better title.
Important to note: I'm new to js and I guess its the reason I can't figure it out by myself.
I have a JSON array returned from a database, the JSON array represent a set of points.
Example of the JSON array:
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...]
I want to make a different array whose elements will be a function and the variables of the function will be the elements from the JSON array, like so:
var coordinates = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(1, 3),
new google.maps.LatLng(2, 3),
....
];
I made a function using forEach that counts the elements of the JSON array (for learning and trying to find a way to what I want) but I cant think of a way make the array mentioned above.
You could use Array map method:
var coordinates = JSON_array.map(function(coordinate) {
return new google.maps.LatLng(coordinate.lat, coordinate.lng);
})
This method gives you an new array based on (1) the original array and (2) how you deal with each element. Here's more detailed doc for the method.
you can also use regular for loop
coordinates = [];
for(var i=0;i<JSON_array.length;i++){
coordinates.push(new google.maps.LatLng(JSON_array[i].lat,JSON_array[i].lng));
}
For mapping element from one array to another you can use Array.prototype.map function like
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...];
var coordinates = JSON_array.map(function(el){ return new google.maps.LatLng(el.lat, el.lng)});
As Grundy commented you can just do:
coordinates = JSON_array.map(function(x) {
return new google.maps.LatLng(x.lat, x.lng);
});
You might want to get your nomenclature straight though, this has nothing to do with JSON.

Pushing info from a form into one of several JS arrays based on class names

I'm trying to sort data taken from a form and insert it into different arrays based on class assignments in the form. I am new to jquery and JS so this could be totally off base but here's what I'm trying to do:
<input type="text" id="word1" class="noun">Noun
and the scripts:
var noun = [];
// code that cycles through the form cut out.....
// here is the trouble spot:
var thing = $(this).val();
var whichArray = $(this).attr('class');
whichArray.push(thing);
Now if console.log the values everything looks good - I get the right info in both thing and whichArray but that push() command doesn't work.
I think the problem is that whichArray is a String, not an Array. You need to actually retrieve the array named whichArray. So you could modify your code thus:
var arrays = {};
arrays["noun"] = noun;
// your code here, then:
arrays[whichArray].push(thing);

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

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);

Categories