Return values in multiple arrays - javascript

My program is returning values in single array: ["addEcommerceItem", "hat", 29.99, "addEcommerceItem", "belt", 19.99];
I am trying to acheive (["addEcommerceItem", "hat", 29.99], ["addEcommerceItem", "belt", 19.99]);
Can anyone make suggestion
products = [
["hat", 29.99],
["belt", 19.99]
]
var testArray = new Array();
for(i in products){
testArray.push('addEcommerceItem');
testArray.push(products[i]);
}
var json = JSON.stringify(testArray);
<script type="text/javascript">
var _paq = _paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
_paq.push(json);
</script>

First of all, don't use for in enumerations on arrays.
Now, there are two ways of approaching the result you want. First, you can simply alter the existing array by prepending that item to every of them:
for (var i=0; i<products.length; i++)
products[i].unshift("addEcommerceItem");
console.log(JSON.stringify(products));
If that's not what you want, you would construct a new array rather:
var _paq = […]; // somewhere
for (var i=0; i<products.length; i++)
_paq.push(["addEcommerceItem"].concat(products[i]));
console.log(JSON.stringify(_paq));
Instead of the concat, you could of course use a second loop:
var _paq = […]; // somewhere
for (var i=0; i<products.length; i++) {
var product = products[i],
temp = [];
temp.push("addEcommerceItem";
for (var j=0; j<product.length; j++)
temp.push(product[j]);
_paq.push(temp); // push each array individually
}
console.log(JSON.stringify(_paq));

Just write what you want to happen: replace each sub-array with its elements preprended by "addEcommerceItem". You could use concat for that:
function prepend(item) { return ["addEcommerceItem"] . concat(item); }
Or, if you prefer,
function prepend(item) { item.unshift("addEcommerceItem"); return item; }
Then it's just
function transform(products) { return products . map(prepend); }
Sample usage:
>> products = [ ["hat", 29.99], ["belt", 19.99] ]
>> transform(products)
<< [ ["addEcommerceItem","hat",29.99], ["addEcommerceItem","belt",19.99] ]
To call _paq.push with each item in the resulting array as one argument, then
_paq.push.apply(_paq, transform(products))
In ES6:
var prepend = item => ["addEcommerceItem", ...item];
var transform = products => products . map(prepend);
_paq.push(...transform(products));

To achieve your desired output, I've modified the for-loop to splice in the additional value to the products array instead of pushing it to the testArray.
var testArray = new Array();
for (var i=0; i < products.length; i++){
products[i].splice(0,0,'addEcommerceItem');
testArray.push(products[i]);
}
A JS Bin demonstrating the results can be seen here.

Related

get array of arrays looping through HTML table

I have this bunch of code
var rows = document.querySelectorAll('.workRow')
var codes = []
for(var i=0;i<rows.length;i++){
var timeCodesInputs = rows[i].getElementsByClassName('xCell')
for(var j=0;j<timeCodesInputs.length;j++){
if(timeCodesInputs[j].innerHTML == "x"){
codes.push(timeCodesInputs[j].dataset.dataHour)
}
}
}
it works ok but it pushed everything to one array. What I want to get an array of arrays where one array if the data from one row. How to do it?
Ciao, try to push row data in one array and then push this array into codes array like:
var rows = document.querySelectorAll('.workRow')
var codes = []
for(var i=0;i<rows.length;i++){
var rowArray = [];
var timeCodesInputs = rows[i].getElementsByClassName('xCell')
for (var j=0;j<timeCodesInputs.length;j++){
if(timeCodesInputs[j].innerHTML == "x"){
rowArray.push(timeCodesInputs[j].dataset.dataHour)
}
}
codes.push(rowArray)
}

adding an array into an array at a particular position (based on key value) in javascript

I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO

Rearranging Elements For Array of Array

I am trying to rearrange elements in an array of arrays but have been unsucessful. Can anyone offer suggestions? Here are two options I have tried. I want to swap/switch places for the first and second elements.
arr1 is an array of arrays (i.e. arr[][]) so I created arr2 to be an updated arr1
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
arr2[n][0] = arr1[n][1];
arr2[n][1] = arr1[n][0];
}
The other thing I tried was:
function order(arr[]){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3]];
}
var arr2 = order(arr1);
You also need to create a new array for each item:
var arr2 = [];
for(var n = 0; n < arr1.length; n++) {
arr2[n] = [arr1[n][1], arr1[n][0]];
}
it's quite easy:
var a = arr1[n][0];
arr2[n][0] = arr1[n][1];
arr2[n][1] = a;
you need to save the first value as a variable, because if you do as you did(arr2[n][0] = arr1[n][1];), your two array indexes will have the same value.
You did:
a = 1, b = 2;
a = b;
b = a;
Which resolves in a = 2, b = 2
Also, your code as it is now, doesn't work. You need to create a new array for the simulation of multidimensional arrays in javascript.
for(i = 0; i < (yourdesiredamountofarrays); i++)
{
yourarray[i] = new Array();
}
The first example you need to use a temporary variable for the switch:
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
var tempVal = arr1[n][1];
arr2[n][1] = arr1[n][0];
arr2[n][0] = tempArr;
}
The second example, in JS the variable shouldn't have brackets next to it, as it's just a loosely typed variable name.
function order(arr){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3], arr[n][4]];
}
var arr2 = order(arr1);
Next time, before asking you should check the console. The stackoverflow wiki page on JS has lots of great resources for learning to debug JS.

Form an array from the for-loop

I have a for loop in which I am getting all the values one by one but I need to form those values into one array.
Can any one let me know how to get form all the values into one array.
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
var yourArray = [];
yourArray.push(marray);
console.log(marray);
}
Output getting from the above code is : ["0123"] and ["3456"]
But the expected output is ["0123","3456"]
You are creating a new yourArray for each loop iteration. Instead of doing that, create it just once before starting the loop:
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
Note that I have changed the code to read yourArray.push(mId) because from the question it seems that's what you want -- not yourArray.push(marray).
A more compact way of doing the same is to use the array map function like this:
var yourArray = marray.map(function(row) { return row.id; });
This last version won't work out of the box in IE 8, so if you care about that you need to take appropriate measures.
decalare variable in outside for loop..
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mid);
}
console.log(yourArray);
Initialise yourArray before the loop
Try this
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
The var yourArray is initialized to null each time you enter the loop. Define it outside loop.

One dimensional to two dimensional array javascript

First I have an array like:
arr = [[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a]]
I can 'flatten' it using
arr = Array.prototype.concat.apply([],arr)
or using a for-next loop and push.apply
Then I got:
[r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a]
How do I get it back to its original format as easy as possible?
var newArr = [];
while(arr.length){
newArr.push(arr.splice(0,4));
}
Something like this, perhaps:
var old = [];
for (var index = 0; index < arr.length; index+= 4)
old.push( arr.slice(index, index + 4) );

Categories