[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

How do I add the numbers of an array

I have a list consisting of numbers and - unfortunately - a suctraction sign.
var saleItems=sales[i].toString();
trace(saleItems) results in the below
//
1
-
-
3
-
-
1
-
1
-
-
-
3
-
-
-
-
-
1
2
2
-
1
1
-
9

Open in new window


How do I add the numbers and how do I remove the subtraction-signs.
0
petersego
Asked:
petersego
  • 3
  • 2
1 Solution
 
dgofmanCommented:
var validChars:String = "0123456789";
var saleItems:Array = ["1", "2", "+", "-", "3", "4"];
for(var i:Number = saleItems.length - 1; i >= 0; i--){
	if(validChars.indexOf(saleItems[i]) == -1)
		saleItems.splice(i, 1);
}
trace(saleItems) 

Open in new window

0
 
petersegoAuthor Commented:
Thanks, that seems to work, but how do I get a sum of the numbers. In your example the sum 10.
0
 
dgofmanCommented:
You can use string.length and charAt function for substring and compare each symbol in your area item. I cannot code for now but is
Loop inside loop. Try to write code if not I will submit my version an in hour

0
 
dgofmanCommented:
var validChars:String = "0123456789";
var saleItems:Array = ["1", "2", "+", "-", "3", "4", "1c", "10"];
for(var i:Number = saleItems.length - 1; i >= 0; i--){
	var item:String = saleItems[i];
	for(var c:Number = 0; c < item.length; c++){
		if(validChars.indexOf(item.charAt(c)) == -1){
			saleItems.splice(i, 1);
			break;
		}
	}
}
trace(saleItems)  

//Another solution working for ALL number, but you cannot controll for example skip number 5 or 6
var saleItems:Array = ["1", "2", "+", "-", "3", "4", "1c", "10"];
for(var i:Number = saleItems.length - 1; i >= 0; i--){
	if(isNaN(new Number(saleItems[i])))
		saleItems.splice(i, 1);
}

trace(saleItems)  

Open in new window

0
 
petersegoAuthor Commented:
Thanks, they works fine, but I did a try myself and ended up with this solution.

var total:Array=[];
var sum:Number=0;
var salesItems:Array=["1", "2", "+", "-", "3", "4", "1c", "10"];
for each(var o:Number in salesItems){
    if(!o){
          o=0;
    }
    total.push(o);
}
for (var i:Number = 0; i < total.length; i++){
    sum+=total[i];			
}
trace(sum);      // 20

Open in new window


It seems to work.

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now