Why is the array empty - javascript

I am just starting to learn Unity3D javascript, this is my first try to learn, trying to copy a shuffle Objective-C code snippet i have, and I have the following code:
function Shuffle(theCardArray : Array) {
var dupeArray = new Array();
var count = theCardArray.length;
print("theCardArray: " + theCardArray);
dupeArray = theCardArray;
count = dupeArray.length;
print("A) Count dupeArray: " + count);
print("B) Count dupeArray: " + dupeArray.length);
theCardArray.Clear();
for (var i = 0; i < count; i++) {
// Select random element between i and the end of the array to swap it
var nElements = count - i;
var n = Random.Range(0, nElements);
print("#1");
print("C) Count dupeArray: " + dupeArray.length);
print("dupeArray: " + dupeArray);
var dummyString = dupeArray[n];
print("#2");
theCardArray.Push(dummyString);
print("#3");
}
}
I get the following in my prints:
theCardArray: back,D2,D3,D4,D5,D6,D7,D8,D9,D10,DJ,DQ,DK
A) Count dupeArray: 13
B) Count dupeArray: 13
'#1'
C) Count dupeArray: 0
At B) the dupeArray have 13 entities and at C) the dupeArray is empty!
Could someone please explain to me why the array is empty at C)?
BTW, i know there are other ways in Unity3D to achieve the same thing but this is for learning!
The final and real solution I came up with for this is:
Call ShuffleThis with:
arr = ShuffleThis(arr);
The Shuffle function:
function ShuffleThis(theCardArray : Array) : Array {
var size : int = theCardArray.length;
for (var i : int = 0; i < size; i++) {
var indexToSwap : int = Random.Range(i, size);
var oldValue = theCardArray[i];
theCardArray[i] = theCardArray[indexToSwap];
theCardArray[indexToSwap] = oldValue;
}
return theCardArray;
}
Source: Fisher-Yates Shuffle with UnityScript

It's because the array dupeArray is just a reference to the original array theCardArray, so when you clear the original array you are also clearing the duplicate array; by reference.
In order to resolve your issue you should clone the original array, this can be done using slice like this...
var dupeArray = theCardArray.slice(0);
Alternatively, it can also be done using the jQuery extend approach like this...
var dupeArray = $.extend(true, [], theCardArray);

Related

Manipulate more javascript array based on another array

I've a strange thing to do but I don't know how to start
I start with this vars
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
So to start all the 3 array have the same length and the very first operation is to see if there is a duplicate value in sky array, in this case the 0 is duplicated and only in this case is at the end, but all of time the sky array is sorted. So I've to remove all the duplicate (in this case 0) from sky and remove the corresponding items from base and sum the corresponding items on ite. So if there's duplicate on position 4,5 I've to manipulate this conditions. But let see the new 3 array:
var new_base = [1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var new_sky = [0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var new_ite = [139,38,13,15,6,4,6,3,2,1,2,1,1,1];
If you see the new_ite have 139 instead the 64,52,23, that is the sum of 64+52+23, because the first 3 items on sky are the same (0) so I remove two corresponding value from base and sky too and I sum the corresponding value into the new_ite array.
There's a fast way to do that? I thought a for loops but I stuck at the very first for (i = 0; i < sky.length; i++) lol, cuz I've no idea on how to manipulate those 3 array in that way
J
When removing elements from an array during a loop, the trick is to start at the end and move to the front. It makes many things easier.
for( var i = sky.length-1; i>=0; i--) {
if (sky[i] == prev) {
// Remove previous index from base, sky
// See http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript
base.splice(i+1, 1);
sky.splice(i+1, 1);
// Do sum, then remove
ite[i] += ite[i+1];
ite.splice(i+1, 1);
}
prev = sky[i];
}
I won't speak to whether this is the "fastest", but it does work, and it's "fast" in terms of requiring little programmer time to write and understand. (Which is often the most important kind of fast.)
I would suggest this solution where j is used as index for the new arrays, and i for the original arrays:
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
var new_base = [], new_sky = [], new_ite = [];
var j = -1;
sky.forEach(function (sk, i) {
if (!i || sk !== sky[i-1]) {
new_ite[++j] = 0;
new_base[j] = base[i];
new_sky[j] = sk;
}
new_ite[j] += ite[i];
});
console.log('new_base = ' + new_base);
console.log('new_sky = ' + new_sky);
console.log('new_ite = ' + new_ite);
You can use Array#reduce to create new arrays from the originals according to the rules:
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330];
var sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17];
var ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1];
var result = sky.reduce(function(r, n, i) {
var last = r.sky.length - 1;
if(n === r.sky[last]) {
r.ite[last] += ite[i];
} else {
r.base.push(base[i]);
r.sky.push(n);
r.ite.push(ite[i]);
}
return r;
}, { base: [], sky: [], ite: [] });
console.log('new base:', result.base.join(','));
console.log('new sky:', result.sky.join(','));
console.log('new ite:', result.ite.join(','));
atltag's answer is fastest. Please see:
https://repl.it/FBpo/5
Just with a single .reduce() in O(n) time you can do as follows; (I have used array destructuring at the assignment part. One might choose to use three .push()s though)
var base = [1,1,1,2,3,5,7,9,14,19,28,40,56,114,232,330],
sky = [0,0,0,3,4,5,6,7,8,9,10,11,12,14,16,17],
ite = [64,52,23,38,13,15,6,4,6,3,2,1,2,1,1,1],
results = sky.reduce((r,c,i) => c === r[1][r[1].length-1] ? (r[2][r[2].length-1] += ite[i],r)
: ([r[0][r[0].length],r[1][r[1].length],r[2][r[2].length]] = [base[i],c,ite[i]],r),[[],[],[]]);
console.log(JSON.stringify(results));

How to format the element inside an array?

I have three arrays for example:
var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";
for (var i = 0; i < name.length; i++) {
temp = name[i] + " " + type[i];
all.push(temp);
}
for (var i = 0; i < name.length; i++) {
// I call here function to display all element of array `all`
}
The output is:
wheel car
rectangle shape
moon sky
But the format of output is not nice. I want to shift the element of array type before add them to array all, so I want the output to be like:
wheel car
rectangle shape
moon sky
My question is: how can I shift elements of the array to add them to another array and store them in a way that allows to me to display the elements like form above ?
But the form of output not nice
If you simply want to format the output in a better way, then try console.table
var name1 = [ "wheel","rectangle","moon" ];
var type = [ "car" , "shape", "sky"];
var all=[];
for (var i = 0; i< name1.length; i++)
{
all.push({ name : name1[i], type: type[i] });
}
console.table(all);
Try this fiddle to see the actual output since stack-snippet alters the behaviour of console api
You should calculate which is the longest string in the first array so to know in advance how many spaces you need to append to correctly pad the string
var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];
/* sorting the values of the first array by length desc,
* then get the length of the first element
*/
var padding = n.sort(function(a, b) {
return a.length <= b.length;
})[0].length + 1;
n.forEach(function(el, i) {
all.push(el + " ".repeat(padding - el.length) + t[i]);
});
Output
"rectangle car"
"wheel shape"
"moon sky"
codepen demo
First loop over the array and find the max length. Then loop again and add spaces.
<script >
var name=["wheel","rectangle","moon"];
var type=["car","shape","sky"];
var all=[];
var i=0;
var maxLength=0;
string temp=" ";
String.prototype.padLeft= function(len, c){
var r = '';
while(r.length < len) r += c;
return s+r;
}
for (i = 0; i< name.length; i++)
{
maxLength = Math.max(maxLength, name[i].length+type[i].length+1;
}
for (i = 0; i< name.length; i++)
{
temp=name[i]+type[i].padLeft(maxLength-name[i].length-type[i].length);
all.push(temp);
}
</script >
I would do as follows;
var id = ["wheel","rectangle","moon"],
type = ["car","shape","sky"];
id.longestStringLength = Math.max(...id.map(s => s.length));
type.longestStringLength = Math.max(...type.map(s => s.length));
id = id.map((s,_,a) => s + " ".repeat(a.longestStringLength-s.length));
type = type.map((s,_,a) => " ".repeat(a.longestStringLength-s.length) + s);
console.log(id,type);
Use \t instead of space while concatenating to make it aligned.
Why don't you just add tab '\t' and it will give you the desired output. Or you can append fixed number of spaces between the two array items.

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

javascript how to pass each element in an array to different var

I am new to javascript and recently have a problem to passing elements from array to var.
For example, I have an array like var anArray = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]], and I have 3 different var a , b and c.
after some loop codes,
what I would like to see is:
while a=a1, b should be b1 and c=c1
while a=a2, b=b2 and c=c2
while a=a3, b=b3, c=c3
also pls consider that what if I have array like:
[[a1,a2,a3],[b1,b2,b3]] which will result a=a1 while b=b1, a=a2 while b=b2 etc.
or [[a1,a2],[b1,b2],[c1,c2]] which will result a=a1 while b=b1 and c=c1, a=a2 while b=b2 and c=c2
If my question is still not clear enough, please comments it and I will update it.
I really appreciate all the comments and the code that you have made! Many thanks!
You have a bunch of pieces backwards and in the wrong place:
var anArray = [[1,2],[1,2]];
for(var i=0;i <= anArray.length - 1;i++)
{
for(var j=0;j<anArray[i].length;j++){
var a = anArray[i][j];
var b = anArray[i + 1][j];
alert("a: "+a+" and b: "+b);
}
}
Edit: adjusted after you changed your entire question.
Let say that we have have an array like thisvar anArray = [[1,2,3],[4,5,6]];
and if you want to alert this a=14;b=25;c=36; then you can use this code
var anArray = [[1,2,3],[4,5,6]];
for ( i = 0; i < anArray.length; i++ ) {
var l = anArray[i];
for ( m = 0; m < l.length; m++ ){
this["a"+i+m.toString()] = l[m];
}
}
alert("a = "+ a00 + a10.toString());
alert("b = "+ a01 + a11.toString());
alert("c = "+ a02 + a12.toString());
Where a00=1; a01=2; a02=3; these are the elements of the first array.(the middle nr. tells the array so for the first array we use 0).
Then we have a10=4; a11=5; a12=6; these are the elements of the 2nd array.(the middle nr. tells the array so for the second array we use 1).
All you have to do is just replace this arrayvar anArray = [[1,2,3],[4,5,6]] with yours and let
javascript do its job.
After you clarified your question I got a general idea of what you want. I think this is what you want to achieve. The example is dynamic so that as long as the length of item in the array is equal.
var anArray = [[1,2,3],[4,5,6],[7,8,9]];
for(var j=0;j<anArray[0].length;j++){
var values = [];
for(var i=0;i<anArray.length;i++) {
values[i] = anArray[i][j];
}
//Do what you want with the values below. I chose to show them in a alert message
var text = '';
for(var i=0;i<anArray.length;i++) {
if(text.length>0){ text += ',' };
text += values[i];
}
window.alert('Values: ' + text);
}
PS: There were not 1 but a few things wrong with your code.

Why does the sort() function changes values of numbers in this Array?

var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:" ;
var _array = ["un", "deux", "trois"] ;
var _items = new Array();
for (var t =0; t < _array.length; t++) {
found = _txtString.match(new RegExp(':' + _array[t]+ ':', 'g'));
_items[t] = parseInt(found.length);
//_items.sort();
document.write("<br />" + _items[t] + " " + _array[t]);
}
Hi,
when I run this code, results displayed are properly counted:
2 un
3 deux
2 trois
But when I uncomment the sort() line, count is wrong:
2 un
3 deux
3 trois <=
What I wanted is to sort the result returned by numeric value. What is beyound my understanding is that the sort() function changes the actual value ?! Any clue why ?
Thanks
Because you are sorting, you are changing the order of the array. So when you sort the "3" becomes the last index and it writes that out.
_items[t] = parseInt(found.length); //[2,3,2]
_items.sort(); //[2,2,3]
document.write("<br />" + _items[t] + " " + _array[t]); //here you are reading the last index which is 3
If you want to sort by the count, you need to do it after you calculate everything.
Basic idea:
var _txtString = ":un:-:un:-:deux:-:deux:-:deux:-:trois:-:trois:";
var _array = ["un", "deux", "trois"];
var _items = new Array();
for (var t = 0; t < _array.length; t++) {
found = _txtString.match(new RegExp(':' + _array[t] + ':', 'g'));
_items.push({
count: found.length,
text: _array[t]
});
}
_items.sort(function (a, b) {
return a.count - b.count;
});
for (var i = 0; i < _items.length; i++) {
console.log(_items[i].count, _items[i].text);
}
The sort command in javascript does an in-place sort, meaning it will mutate your array order. When this occurs it simply looks to me like your code is just out of sync to what you are expecting.
There is no way to avoid this unless you make a copy of the array and do a sort on the copy therefore leaving the original array as-is.

Categories

Resources