One dimensional to two dimensional array javascript - 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) );

Related

Substr on an array element if not empty

Hei, I have an array containing some empty strings and some strings with content.
I want to slice down the first 5 letters of those which are not empty strings, and put them into a new array. I also want to keep the empty ones.
example:
myArray = [ "","","123456789","","",""];
var newArray = ["","","12345","","",""]
I tried with for loop with if inside if the myArray[i] is empty then don't do substr(), but I get an error that it is not a function.
I actually don't need to put it into a new array, I just want to put the myArray(i).subsrt(5) value into a splice(), but then I get the error:
VM750:82 Uncaught TypeError: Cannot read property 'substr' of undefined
ES6 with array.map
myArray = [ "","","123456789","","",""];
var newArray = myArray.map((s) => s.substr(0, 5))
It's hard to know what your exact problem is without seeing all of your code, but here is a for loop that goes over all the elements in the first array and takes the first 5 or fewer characters of each string to insert into a new array.
myArray = [ "","","123456789","","",""];
var newArray = [];
for(var i = 0; i < myArray.length; i++) {
newArray.push(myArray[i].substr(0,5));
}
exactly what #le_m says:
myArray = [ "","","123456789","","",""];
var newArray = myArray.map(e => e.substr(0, 5));
You need to use substr for non-empty items:
Like this:
myArray = [ "","","123456789","","",""];
for(var i = 0; i < myArray.length; i++) {
temp = myArray[i];
if (temp && temp != "")
myArray[i] = temp.substr(0, 5);
else
myArray[i] = "";
}

Return values in multiple arrays

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.

JScript Array with custom array index

Consider this, I have a JScript array of arrays.
I want to copy a given index of the array into another array using the same index.
So for example:
MyArray = {[0] = Array, [1] = Array, [2] = Array}
I want to copy the 3rd index [2] into another array, such that the first index is not '0' but '2'.
Giving Me:
MyNextArray[2] = {Array}
Apologies for the pseudo code.
Can I make the copy or do I have to first initialize the array and then set a custom index?
Thanks in advance!
MyArray = {[0] = Array, [1] = Array, [2] = Array}
var MyNewArray = sortRay(MyArray, 2);
function sortRay(Ray, firstNr){
MyNextArray = new Array();
MyNextArray[0] = Ray[firstNr];
for(var i = 0, j = 1; i <= Ray.length, i++){
if(i == firstNr){i++, j = 0;}
MyNextArray[i+j] = MyArray[i];
}
return MyNextArray;
}
shld work

Creating array of objects dynamically based on length

I have the length of my previous object and i need to create a new array of objects based on the length with new key's.
Length = 3;
var newArray = [];
for(var i =0; i <3; i++){
var Object = {};
Object['newKey'] = 1;
newArray.push(Object);
}
This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2].
Am i doing this correctly, please do suggest me if anything wrong or a better way to do this.
Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names)
var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
newArray.push({newKey: 1});
}
but to be honest it's unclear to me exactly what you're trying to accomplish
You could make it slightly more dynamic by referencing the variable for length.
Example updated per comments:
var length = 3,
newArray = [];
for ( var i=0; i<length; i++ ) {
var tempObj = {};
tempObj['newKey'] = 'SomeValue';
newArray.push(tempObj);
}
I didn't really do more than clean up what you have.

Is it possible to initialize multiple Javascript arrays in a loop?

Let's say i have a for loop and i want to initialize multiple arrays in that loop. Can it be achieved like this?:
for (var i = 0; i < 5; i++){
var array+i = [];
}
So that the arrays that will be created are array0,array1,array2,array3,array4?
Any help would be much appreciated :)
You can use a multi dimensional array to tackle this problem:
for(var i=0;i<5;i++){
var array[i]=[];
}
which will result in:
array[0] = []
array[1] = []
array[2] = []
array[3] = []
array[4] = []
hope that helps :)
You can achieve something like that using
JavaScript Two Dimensional
Arrays
Building a MultiDimensional Array in
Javascript
JavaScript Multi-Dimensional
Arrays
JavaScript: Multi-dimensional
Array
You can create an array of arrays:
var arr = [];
for (var i = 0; i < 5; i++) {
arr[i] = [];
}
Or if it must be a global variable (probably not a good idea):
for (var i = 0; i < 5; i++) {
window["array" + i] = [];
}
You could probably eval it out,
for (var i=0;i<5;i++) {
eval("var array"+i+"=[];");
}
But eval is evil, it would make much more sense to just use a 2 dimensional array.
You can just use a two dimensional array.
Example to initialize 10 empty arrays:
let subArrays = Array.from({length: 10}, () => []);
If you're in a browser and willing to do something hacky you can use the top-level object, namely window:
for (var i = 0; i < 5; i++) {
window["array" + i] = [];
}
After doing this, you'll be able to refer to each array as array1 or whichever number you want.
This said, you should probably never actually use this method.

Categories