PDA

View Full Version : 2d arrays !


jsGirl
01-13-2008, 07:18 PM
Hello, Maybe this question isnt directly related to DOM but I will eventually need to do some dom scripting after I am successful with this array.
I have an array:
arrNums = [122379, 198702, 102884, 109231];

now this arrNums resets itself for every post on the page and there might be repeating numbers. I need to write a 2d array myArray['num'] storing numbers and myArray['count'] storing count of each time the number has occured.

arrNums = 122379, 198702, 102884, 109231;

for (i=0; i<arrNums.length; i++){

(j=0; j<myArray['num'].length; j++){
if (myArray['num'][j] == arrNums[i]) { // if this number already exists then increment count}
else {myArray['num'][i] = arrNums[i]; // else set the new number

}


I know I am doing it completely wrong but i desperately need help! :

Trinithis
01-13-2008, 07:48 PM
var arrNums = [122379, 198702, 102884, 109231];

jsGirl
01-13-2008, 07:56 PM
Thanks for your reply! Actually how I am doing it is like this:
var arrNums = "122379, 198702, 102884, 109231";
arrNums = arrNums.split(","); // so this makes an array


I need to loop through myArray's value everytime I have a new number to assign to it to check if that number exists. If it does then increase the counter for that specific number and if it doesnt, then assign that number to myArray. I just dont know how to turn this into programming and whether I need nested loops.

Trinithis
01-14-2008, 01:49 AM
var arrNums = [6, 1, 2, 2, 1, 3, 4, 5, 1, 1, 6];
var myObj = {
num: [],
count: []
};

for(var i = 0; i < arrNums.length; i++) {
var p = myObj.num.indexOf(arrNums[i]);
if(p != -1)
myObj.count[p]++;
else {
myObj.num.push(arrNums[i]);
myObj.count.push(1);
}
}

shyam
01-14-2008, 07:44 AM
another alternative

var ar = [6, 1, 2, 2, 1, 3, 4, 5, 1, 1, 6];
var b = {};
ar.forEach(function(v) {
if ( !b[v] ) {
b[v] = 0;
}
b[v]++;
});


since forEach (or even indexOf is not defined in IE for arrays)
if ( !Array.prototype.indexOf ) {
Array.prototype.indexOf = function(e){
for ( var i = 0; i < this.length; i++ ) {
if ( this[i] == e ) {
return i;
}
}
return -1;
};
}
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(cb) {
var a = [];
for ( var i = 0; i < this.length; i++ ) {
a.push(cb.call(this[i], i, this.length));
}
return a;
};
}

jsGirl
01-14-2008, 05:14 PM
Thank you guys . very helpful!