I'm trying to write a function where I can specify any amount of array, and the return value will be an array containing the contents of all of the specified arrays.
I've done this, but it seems like a really slow and ugly way of doing it:
var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];
function merge(...multi):Array
{
var out:String = "";
for each(var i:Array in multi)
{
out += i.join(',');
}
return out.split(',');
}
trace(merge(ar1, ar2));
Is there an inbuilt and more efficient / nice way of achieving this? The result does not need to be in the same order as the input - completely unsorted is fine.
You can use concat.
If the parameters specify an array, the elements of that array are concatenated.
var ar1:Array = [1,2,3,4,5,6,7,8,9];
var ar2:Array = ['a','b','c','d','e','f','g','h'];
var ar3:Array = ['i','j','k','l'];
var ar4 = ar1.concat(ar2, ar3); // or: ar1.concat(ar2).concat(ar3);
To make a single array out of a 2 dimensional array you can use this function:
private function flatten(arrays:Array):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
// call
var ar4 = [ar1, ar2, ar3];
var ar5 = flatten(ar4);
You can also use varargs to merge multiple arrays:
private function merge(...arrays):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
// call
var ar5 = merge(ar1, ar2, ar3);
I don't know if this method is faster than using loops, but it is a (fancy) quick way to merge 2 arrays. (and it works in Javascript and Actionscript)
var arr1:Array = [1,2,3,4,5]
var arr2:Array = [6,7,8,9,10]
arr1.push.apply(this, arr2); // merge
// arr1.push.call(this, arr2); // don't use this. see comment below
trace(arr1) // 1,2,3,4,5,6,7,8,9,10
function merge(...multi):Array
{
var res:Array = [];
for each(var i:Array in multi)
{
res = res.concat(i);
}
return res;
}
Didnt try it, but something like this would help you.
Related
I've been trying without success to get unique values from an array, after creating the array from getRespondentEmail in google apps script. I've tried to use the set method, the forEach etc for this and each time it returns an empty array or empty curly brackets. This is a sample of my code:
function test(){
var form = FormApp.openById('...');
form.setCollectEmail(true);
var formResponses = form.getResponses();
var getEmails = [];
var uniqueResponses = [...new Set(getEmails)];
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var oneEmail = formResponse.getRespondentEmail();
getEmails.push(oneEmail);
}
Logger.log(uniqueResponses);
}
Does anyone know what the problem might be? I'm stuck. Thank you so much.
In your script, how about the following modification?
Modified script:
function test(){
var form = FormApp.openById('...');
form.setCollectEmail(true);
var formResponses = form.getResponses();
var getEmails = [];
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var oneEmail = formResponse.getRespondentEmail();
getEmails.push(oneEmail);
}
var uniqueResponses = [...new Set(getEmails)];
Logger.log(uniqueResponses);
}
In your script, when var uniqueResponses = [...new Set(getEmails)] is run, getEmails has no value. By this, your issue occurs. In this modification, var uniqueResponses = [...new Set(getEmails)] is used after getEmails has the values. By this, the duplicated values are removed.
Reference:
Set
I have this data inside my controller form:
$scope.reports = [
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
},
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
}
];
The above data is array of objects, I want them to convert in array. I used this code below to convert them in array:
var details=[];
for(var index in $scope.reports){
var tripcode = $scope.reports[index].tickettripcode;
var dateOfDepature = $scope.reports[index].departuredate.split('-');
details.push(tripcode, dateOfDepature[2]);
}
if(details[tripcode][dateOfDeparture[2]]){
details[tripcode][dateOfDeparture[2]] = details[tripcode][dateOfDeparture[2]] +1;
}
else {
details[tripcode][dateOfDeparture[2]] =1;
}
The code is not working fine with me and I do not know why. I have a doubt if I am doing array manipulation in a right way. I have error dateOfDeparture is not defined. I already defined the dateOfDeparture so why I getting this error. I just wanted to get the output which looks like this:
details = Array (
[3] =>Array
(
[10] =>2
)
)
The [3]is tickettripcode and [10] is the day of depaturdate. The 2 means number of departuredate in that date.
Any help would be much appreciated.
This is the link of my fiddle : https://jsfiddle.net/n1bw2u36/
Thanks in advance!
Unfortunately there are a lot of things you should learn about javascript.
By the way, I would expect that you will get what you want with the code like this.
var reports = [
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
},
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
}
];
var table = {};
for (index=0; index<reports.length; index++){
var tripcode = reports[index].tickettripcode;
var dateOfDepature = reports[index].departuredate.split('-');
var date = dateOfDepature[2];
var map = table[tripcode];
if (map===undefined){
map = {};
table[tripcode] = map;
}
if (map[date]===undefined){
map[date] = 0;
}
map[date]++;
}
You can use "table" like this.
console.log(table);
console.log(table[3][10]);
I’m new to Backbone, but I’ve successfully been able to define an array like this on one of my models:
buildMyArray: function() {
var self = this;
var myArray = {};
window.myLibrary.getStuff('myParameter', function(myStuff) {
for (var myKey in myStuff) {
if (myStuff.hasOwnProperty(myKey)) {
var myValue = myStuff[myKey];
myArray[myKey] = myValue;
}
}
self.set({ myArray: myArray });
});
}
However, how can I access that array from other properties? In other words, I want to do something like this:
checkArrayStuff: function(arrayKey) {
//loop through myArray and check value for arrayKey.
//var myArray1 = self.get(myArray);
//var myArray2 = this.get(myArray);
//var myArray3 = myArray;
//var myArray4 = this.myArray;
//var myArray5 = self.get('myArray');
//var myArray6 = this.get('myArray');
var myArray7 = self.myArray;
var can = myArray7[arrayKey];
return can;
}
I’ve tried several variations of self, this, with-and-without-quotes, with-and-without get-method, etc.
I guess you would have to do this
checkArrayStuff: function(arrayKey) {
return this.get('myArray')[arrayKey];
}
this.get('myArray') should work but it looks like your window.myLibrary.getStuff function is asynchronous. That means myArray won't be set until some time after buildMyArray returns. If you give us more context we can make a better recommendation of how to address this such as having buildMyArray call checkArrayStuff after it's done the .set(..) or having buildMyArray return a promise
Is there any dynamic way to convert/clone this object:
var object = {
a: 2,
b: function(){
return this.a;
}
}
Into this kind of function object:
function object(){};
object.a = 2;
object.b = function(){
return this.a;
};
Is this possible? how can I do so dynamically?
You can just copy everything, though I would use the prototype:
function toClass(obj) {
var func = function () {};
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
func.prototype[i] = obj[i];
}
}
return func;
}
A whole other question is how useful this actually is and whether there is a better solution to the underlying problem.
Fiddle: http://jsfiddle.net/pb8mv/
It is a little bit strange that you need such a thing. If I have to guess, I think that you have an object and you want to extend it. I.e. you want to create function based on that object, so you later create multiple instances of it. That's possible and here it is a little snippet showing how:
var object = {
a: 2,
b: function(){
return this.a;
}
}
var extend = function(obj) {
return function() {
return Object.create(obj);
}
};
var Class1 = extend(object);
var ob1 = Class1();
ob1.a = 10;
var Class2 = extend(object);
var ob2 = Class2();
ob2.a = 23;
console.log(ob1.b(), ob2.b());
The result of the script is
10 23
How can I splice an array within another array?
I'm trying to create a game for kids in my class. Some kind of a trivia history question creator. How to splice the MasterArray so that I would get rid of sub-arrays (Hard-England and Medium-England) within the allEnglandArray. Because the "MasterArray.splice()" seem to be affecting - splicing only the allEngland array, or the allFrance array. But I need to get rid of those sub-arrays...
My code:
var Easy-England:Array = ["item1","item2","item3","item4","item5"];
var Medium-England:Array = ["item6","item7","item8"];
var Hard-England:Array = ["item9","item10"];
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
var Easy-France:Array = ["item11","item12","item13","item14","item15"];
var Medium-France:Array = ["item16","item17","item18"];
var Hard-France:Array = ["item19","item20"];
var allFrance:Array = [Easy-France,Medium-France,Hard-France];
// the list of countries goes on and on and on... (Italy, Hungary, etc.)
var allStuff:Array = [allEngland, allFrance, etc.];
var MasterArray:Array;
// FUNCTIONS
// clear MasterArray - first I clear out completely the MasterArray
function clearMasterArray():void
{
MasterArray.splice(0);
}
// update MasterArray - than I fill the MasterArray with data according to checkBoxes
function updateMasterArray():void
{
for (var i:int = 0; i<checkBoxBlock.myCheckBoxes.length; i++)
{
if (checkBoxBlock.myCheckBoxes[i].selected)
{
MasterArray.push(allStuff[i]);
}
}
}
// splice MasterArray - last thing I do is splice the items according to student's proficiency level, referred to as "studentPL".
function spliceMasterArray():void
{
if (studentPL == 1)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(5,5);
}
}
if (studentPL == 2)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(8,2);
}
}
if (studentPL == 3)
{
for (var i:int = 0; i<allStuff.length; i++)
{
trace("no need to splice");
}
}
}
And after this I call those functions in another function in this order...
function creatorFunction():void
{
clearMasterArray();
updateMasterArray();
spliceMasterArray();
}
Instead of:
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
try this:
var allEngland:Array = Easy-England.concat(Medium-England, Hard-England);
This way you will have a 'flat' array (no sub-arrays), so it will be easier to deal with.