Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-05-2013, 01:52 PM   PM User | #1
juliushg
New Coder

 
Join Date: Jul 2012
Location: Mexico
Posts: 45
Thanks: 9
Thanked 0 Times in 0 Posts
juliushg is an unknown quantity at this point
I think this array handling can be improved

I created an array the usual way: var subtotal = new Array();, but I created elements using an index from another set of data, with several numbers as index, like this:

Code:
subtotal[360]="23.50"
subtotal[459]="8"
subtotal[825]="12.50"
subtotal[15253]="17"
and so on, so this means that from positions 0 to 359 the values are empty, and so are from 361 to 458, etc.

I have two questions:

1) Is this a good way to do this, or the empty positions are consuming extra memory?

and

2) Now I need to sum all the existent values, I guess that with a For loop would be the normal way, but I'm afraid that

Code:
var sum = new Number();sum=0;
for (var i=0;i<subtotal.length;i++){
sum=sum+subtotal[i];
}
won't make the job. Is there a way to sum all the existent values in an array? Or do you recommend any efficient way to accomplish the same?

Note that the index numbers are "product ids", and I made it that way to address the content by those ids.

Thanks in advance.
juliushg is offline   Reply With Quote
Old 01-05-2013, 03:04 PM   PM User | #2
mrhoo
Regular Coder

 
Join Date: Mar 2006
Posts: 708
Thanks: 30
Thanked 127 Times in 118 Posts
mrhoo will become famous soon enoughmrhoo will become famous soon enough
//
The array methods map and reduce do not apply their function arguments to undefined elements-

Code:
var subtotal= [];
subtotal[360]= "23.50";
subtotal[459]= "8";
subtotal[825]= "12.50";
subtotal[15253]= "17";
subtotal.map(Number).reduce(function(a, b){
	return a+b;
}).toFixed(2);
/* returned value: (String)
61.00
*/


If you need to support older(<IE8) browsers you need a shim for the advanced array functions-
Code:
Array.prototype.map= Array.prototype.map || function(fun, scope){
	var T= this, L= T.length, A= Array(L), i= 0;
	if(typeof fun== 'function'){
		while(i<L){
			if(i in T){
				A[i]= fun.call(scope, T[i], i, T);
			}
			++i;
		}
		return A;
	}
}
Array.prototype.reduce= Array.prototype.reduce || function(fun, temp, scope){
	var T= this, i= 0, len= T.length, temp;
	if(typeof fun=== 'function'){
		if(temp== undefined) temp= T[i++];
		while(i<len){
			if(i in T) temp= fun.call(scope, temp, T[i], i, T);
			i++;
		}
	}
	return temp;
}
You could also use a 'tight' array of objects-

Code:
function Sub(i, amount){
	this.index= i;
	this.amount= Number(amount);
}
var subtotal= [
	new Sub(360, "23.50"),
	new Sub(459, "8"),
	new Sub(825, "12.50"),
	new Sub(15253, "17")
];
var sum= 0;
for(var i= 0, L= subtotal.length;i<L;i++){
	sum+= subtotal[i].amount;
}

sum.toFixed(2)

/* returned value: (String)
61.00
*/
mrhoo is offline   Reply With Quote
Old 01-05-2013, 04:14 PM   PM User | #3
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Code:
var sum = new Number();sum=0;
for (var i=0;i<subtotal.length;i++){
    sum=sum+subtotal[i];
}
compare this with:

Code:
for (item in subtototal) {
    sum = sum + subtotal[item];
}
Code:
for (item in subtotal) {
    console.log(item, subtotal[item]);
}

Output: 
360 23.50
459 8
825 12.50
15253 17
That is, JavaScript does not "fill in the gaps". Arrays are objects and the indices are attributes of the (array-)object.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS

Last edited by AndrewGSW; 01-05-2013 at 04:24 PM..
AndrewGSW is offline   Reply With Quote
Users who have thanked AndrewGSW for this post:
juliushg (01-06-2013)
Old 01-05-2013, 10:27 PM   PM User | #4
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
It' always possible to use an object to avoid to define a 15554 length array !

Code:
var subtotal= {};
subtotal[360]= 23.50; // a number without " "!
subtotal[459]= 8;
subtotal[825]= 12.50;
subtotal[15253]= 17;
sum=0;
for (i in subtotal) sum+=subtotal[i];
alert(sum.toFixed(2));

Last edited by 007julien; 01-05-2013 at 10:30 PM..
007julien is offline   Reply With Quote
Old 01-05-2013, 10:41 PM   PM User | #5
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
An array is an object, but then so is a date.. and anything else for that matter

Code:
var subtotal= [];
subtotal[360]= "23.50";
subtotal[459]= "8";
subtotal[825]= "12.50";
subtotal[15253]= "17";

subtotal.Santa = "Claus";
console.log(subtotal.Santa, subtotal['Santa']); // Claus Claus

subtotal.xmas = function () { alert('Ho! Ho!'); };
subtotal.xmas();

var dte = new Date();
dte.season = "Winter";
console.log(dte.season); // Winter
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-05-2013, 10:45 PM   PM User | #6
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Quote:
It' always possible to use an object to avoid to define a 15554 length array !
The array does not have that number of elements. The .length will be reported as 15554, as this is one more than the largest index, but the actual length - the number of elements - is four - as my previous code confirmed:

Code:
for (item in subtotal) {
    console.log(item, subtotal[item]);
}

Output: 
360 23.50
459 8
825 12.50
15253 17
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-05-2013, 10:58 PM   PM User | #7
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Code:
var newArray = [];
newArray[12] = "whatever";
newArray[50] = "hi";
newArray[34] = "what";
newArray['54'] = "Whoa!";
alert(newArray.length); // 55
alert(newArray['12']); // whatever
for (item in newArray) {
    console.log(newArray[item]);
}

Output:
whatever
what
hi
Whoa!
When we define array elements using a number [12] we are creating object-attributes, rather than indices. However, JavaScript realises that it is a number and uses it to re-order (but not necessarily physically..) all those elements that also have a number as attribute. Because JS is (very) loosely typed, it also recognises '12' as being a number, and so would order this element as well.

When we use numbers as the attribute (index) JS compares it with all other numerical-indices, and uses the largest of these numbers plus one as the .length of the object/array.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS

Last edited by AndrewGSW; 01-05-2013 at 11:07 PM..
AndrewGSW is offline   Reply With Quote
Old 01-06-2013, 12:36 AM   PM User | #8
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
Try this to count the number of array elements !

Code:
var subtotal= [];
subtotal[360]= "23.50";
subtotal[459]= "8";
subtotal[825]= "12.50";
subtotal[15253]= "17";
alert(subtotal.length+'\n'+subtotal)
007julien is offline   Reply With Quote
Old 01-06-2013, 01:14 AM   PM User | #9
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Code:
var subtotal= [];
subtotal[36]= "23.50";
subtotal[49]= "8";
subtotal[23]= "12.50";
//subtotal[15253]= "17";
//console.log(subtotal.length+'\n'+subtotal)
//console.log(subtotal); // undefined, undefined..
console.log(subtotal[40] instanceof Object); // false
// console.log(subtotal[40] instanceof undefined); // TypeError
If something in JavaScript is not an Object then it does not exist.. because everything in JS, apart from primitives, is an instance of Object.

But I recall having this discussion before: I don't think it will lead to a conclusion

[Did IE used to reserve space..? I can't recall.]
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-06-2013, 05:57 AM   PM User | #10
juliushg
New Coder

 
Join Date: Jul 2012
Location: Mexico
Posts: 45
Thanks: 9
Thanked 0 Times in 0 Posts
juliushg is an unknown quantity at this point
Thumbs up

Thanks to all!

Andrew, I'm not so experienced and didn't know the for (item in subtotal) but that did the trick. And yes, there are only those items in the array, not 15253 or whatever the highest index is, but that makes me think... then how "lenght" works? I always thought the lenght method reported the total of "occupied cells" in an array.
juliushg is offline   Reply With Quote
Old 01-06-2013, 09:27 AM   PM User | #11
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
Null is not an object. It exists like subtotal[100] which is undefined !

Last edited by 007julien; 01-06-2013 at 09:29 AM..
007julien is offline   Reply With Quote
Old 01-06-2013, 10:04 AM   PM User | #12
juliushg
New Coder

 
Join Date: Jul 2012
Location: Mexico
Posts: 45
Thanks: 9
Thanked 0 Times in 0 Posts
juliushg is an unknown quantity at this point
Oh, now I see the explanation for what I asked about lenght in Andrew's fourth post.
juliushg is offline   Reply With Quote
Old 01-06-2013, 02:52 PM   PM User | #13
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Quote:
Originally Posted by 007julien View Post
Null is not an object. It exists like subtotal[100] which is undefined !
Code:
alert(typeof null); // object
But this conversation will lead no where: it is undefined.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-07-2013, 10:03 AM   PM User | #14
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,452
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by juliushg View Post
Thanks to all!

Andrew, I'm not so experienced and didn't know the for (item in subtotal) but that did the trick. And yes, there are only those items in the array, not 15253 or whatever the highest index is, but that makes me think... then how "lenght" works? I always thought the lenght method reported the total of "occupied cells" in an array.
no, length is the highest index of the array, not the filled slots. this allows for arrays to be pre-allocated. compare with VB's ubound() function.

since js is scripted, this is more of a wink and nod to traditional programming than anything, although it does allow bounds checking, and a very simple and fast way to empty an array by setting length to zero.

null is indeed an object, and it is not undefined. i suggest reading the spec for the gruesome details.
just know that like 0, false, and undefined, Boolean(null) is false.

null doesn't come up very often, but when it does, it's usually used by the DOM to differentiate between something that doesn't exist like document.click (undefined) versus something that's uninitiated, like document.onclick (null)


one trick for counting "populated" elements is by using Object.keys():


Code:
var subtotal= [1,2,3]; // 3 elements

subtotal[360]= "23.50"; // add a fourth element

subtotal[365]= null; // add a fifth element (note that null is not undefined)

Object.keys(subtotal).length // === 5
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.8% IE9:11.4% IE10:6.5%

Last edited by rnd me; 01-07-2013 at 10:13 AM..
rnd me is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:57 PM.


Advertisement
Log in to turn off these ads.