Merge Javascript arrays within a recursive function - javascript

I'm running into trouble concatenating "two" arrays during recursion. I start with an empty array and during the function I concatenate it with the new array. The concatenated version becomes the array which is again concatenated with another array within the same function. Following is what I want:
var oldArray = [];
for (i=0; i<10; i++) {
var newArray = [i];
oldArray = oldArray.concat([newArray]);
}
document.write(oldArray);
produces: [0,1,2,3,4,5,6,7,8,9]
But if I use my actual production code I get a two steps forward, one step back sort of effect.
written in angular. go() is the wrapping function
var accounts = [];
$http.get('/api/account/', {params:{page:page}}).then(function (result) {
var count = result.data.count,
totalPages = Math.ceil(count/10),
results = result.data.results;
accounts = accounts.concat(results);
if (page < totalPages) {
page++;
go(page);
}
return accounts;
});
produces: [0,1,0,2,1,3,2,4,3,5,4,6,5,7,6,8,7,9]

Related

Turn loop in to arrow function Javascript

I have a simple loop I want to turn into an arrow function
The function deletes all rows from the mainArray when there is a match in columns B or C with data in searchArray
removeROW_LOOP() works but removeROW_ARROW() does not
I get the error when running removeROW_ARROW() Exception: The number of columns in the data does not match the number of columns in the range. The data has 14 but the range has 21.
Thanks for any assistance with this
My data looks like
mainArray
searchArray
results
Loop (works)
function removeROW_LOOP() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
const searchArray = ss.getSheetByName('Helper_(ignore)').getDataRange().getDisplayValues().flat();
const mainArray = ss.getSheetByName('Connections').getDataRange().getDisplayValues();
let result = [];
for (var i = 0; i <= searchArray.length-1; i++) {
result = removeROW(mainArray, searchArray[i]);
}
const sht = ss.getSheetByName('AAA');
sht.clear()
sht.getRange(1,1, result.length, result[0].length).setValues(result);
}
My attempt at arrow function (does not work)
function removeROW_ARROW() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
const searchArray = ss.getSheetByName('Helper_(ignore)').getDataRange().getDisplayValues().flat();
const mainArray = ss.getSheetByName('Connections').getDataRange().getDisplayValues();
const result = searchArray.map(s => removeROW(mainArray, s));
const sht = ss.getSheetByName('AAA');
sht.clear()
sht.getRange(1,1, result.length, result[0].length).setValues(result);
}
and
function removeROW(array, item) {
array = array.filter(a => a[1]!=item && a[2]!=item);
return array
}
I don't think the problem is function vs. arrow function. Your refactor actually changes the behavior significantly.
removeROW_LOOP() will reset result upon each iteration with the newly filtered array. However, in removeROW_ARROW(), result will be an array of arrays. Specifically, each item in the result will be a filtered version of mainArray with only one searchArray entry filtered out of it.
I think you want somthing along these lines:
function removeUPDATED() {
// ...
const result = mainArray.filter(x => !searchArray.includes(x[0]) && !searchArray.includes(x[1]));
// ...
}
I might have included a bug there, but I think it demonstrates the approach you want.

Extract a value from a Custom Javascript array when it's a component of a string value within an array

I'm looking to extract the values 'adult' and '2ndclass' from this custom javascript array in separate javascript variables for each value. Anyone has any ideas on how to do this?
In the following case, there are 2 products added to cart but I would like to have the flexibility to always grab any existing values for each product that is added to cart regardless of the amount added. Is that possible?
[
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**',
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**'
]
Thank you in advance for your help
You can also use RegExp to get those values out.
var arr = [
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**",
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**"
];
var results = [];
for (var i=0; i < arr.length; i++) {
var matches = arr[i].match(/\*\*(.+)\/(.+)\*\*/);
if(matches && matches.length >= 3)
results.push([matches[1], matches[2]]);
}
console.log(results);
You can try the code here https://jsfiddle.net/p84eftL7/1/
First of all i didn't get your question completely. But as far as i can understand you want those 2 values at the end of the strings from an array. You can try something like this
var a, b;
for(s in YOUR_ARRAY){
[...other, a, b] = YOUR_ARRAY[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
Let me explain myself, Firstly you would require to iterate over your array thats why we have a 'for' loop here. Then for each string which is given by 'YOUR_ARRAY[s]' you are splitting the string with '/' as a delimiter. Rest of the thing is pretty simple.
For your reference go through these links
https://www.w3schools.com/js/js_loop_for.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
UPDATE:
As mentioned in the comments. If you want to have a function for this then
function processValues(arr){
var a, b;
for(s in arr){
[...other, a, b] = arr[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
}
processValues(YOUR_ARRAY);
In the end what I did was the following
As I had to reference back to the name of the variable I used the following to slice up the array so I could reference that using index numbers for the values I needed to retrieve:
function() {
var myStringArray = {{MY_ARRAY}};
var arrayLength = myStringArray.length;
var output = []
for (var i = 0; i < arrayLength; i++) {
var string = myStringArray[i].split("/",4)
/*pull index 2 and 3 from string and convert to string*/
output.push(string)
}
return output
}
After that I had to loop the new array that was being pushed out of the info as mentioned above
Since I only needed to split up particular indices from that NEW_ARRAY_2, I used the following to do that
function() {
var products = {{NEW_ARRAY_2}};
var arr = []
for (var i=0; i < products.length; i++) {
var prod = products[i];
var matches = prod[2];
arr.push(matches);
}
var list = arr.join(', ')
return list
}
SAMPLE RETURN for 2 products: 'adult, youth'
Thank you for your support

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Sorting 2D javascript array

I have an array containing a list of tags and count.
tags_array[0] = tags;
tags_array[1] = tags_count;
I need to sort the arrays base on the count so that I can pick out the top few tags.
Sort one, while storing the sort comparisons. Then sort the other using those results:
var res = [];
tags_count.sort( function( a, b ){ return res.push( a=a-b ), a; } );
tags.sort( function(){ return res.shift(); } );
Supposing tags and tags_count are 2 arrays of same length, I would first build a proper array of objects :
var array = [];
for (var i=0; i<tags_count.length; i++) {
array.push({tag:tags[i], count:tags_count[i]});
}
And then sort on the count :
array.sort(function(a, b) {return a.count-b.count});
If you need to get your arrays back after that, you may do
for (var i=0; i<array.length; i++) {
tags[i] = array[i].tag;
tags_count[i] = array[i].count;
}
Demonstration
Assuming that both tags and tags_count are arrays with the same length (that part of the question wasn't too clear), the following is one way to do the trick.
var tags_array = new Array();
for (var i = 0; i < tags.length; i++)
{
tags_array[i] = {};
tags_array[i].tagName = tags[i];
tags_array[i].tagCount = tags_count[i];
}
tags_array.sort(function(a,b){return b.tagCount-a.tagCount});
One should note that it might be possible to structure the data in this way from the start instead of rewriting it like this, in which case that is preferable. Likewise, a better structure can be used to save the data, but this will work.

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories