Reputation: 79
element.all(by.tagName('strong')).count().then(function (number) {
for (let i = 2; i < number; i=i+3) {
element.all(by.tagName('strong')).get(i).getText().then(function (text2) {
var text3 = text2.split(" ");
var price = text3[1];
console.log(price);
});
}
});
Output: 65000 50000 100000 85000
Here i wanted to get the sum of all the values. Can anyone please help me in getting the sum of all the values.
Upvotes: 1
Views: 1623
Reputation: 71
You can try something like this using .reduce
let sum = element.all(by.tagName('strong')).reduce(function(acc, elem) {
return elem.getText().then(function(text) {
var text3 = text2.split(" ");
var price = text3[1];
return acc + price;
});
}, 0);
UPD:
.reduce
callback also accepts index if you want to skip particular elements.
let sum = element.all(by.tagName('strong')).reduce(function(acc, elem, index) {
if ((index - 2) % 3 == 0) {
return acc + 0;
}
return elem.getText().then(function(text) {
var text3 = text2.split(" ");
var price = text3[1];
return acc + price;
});
}, 0);
Upvotes: 1
Reputation: 32076
You need to keep track of a total
variable, that you add to for each element's text you want to compare.
You need to convert the text of the element into a number. parseFloat()
is one way to do that.
When working with async code (Promises, .then(), etc), you can only use values by chaining another .then()
to the promise chain, to make sure the value is available. If you try to log total
outside of a .then()
, that console.log will execute long before your text totalling code runs.
Summing up, here's an example, that also removes the need for an extra element grab, since it looks like you can use .getText()
on a collection:
let total = 0;
element.all(by.tagName('strong')).getText().then(function(strongTags) {
for (let i = 2; i < strongTags.length; i = i + 3) {
total += parseFloat(strongTags[i].split(' ')[1]);
}
return total;
}).then(function(total) => {
console.log('The total is', total);
});
Upvotes: 3