How to get the last element in an object?
Example:
$scope.sample =[
{“num” : “1”,
{“num”: “2”,
{“num”: “3”}
]
How can I get 3 and add it to 2? In short, how can I get the sum of the last 2 elements in an object?
How to get the last element in an object?
Example:
$scope.sample =[
{“num” : “1”,
{“num”: “2”,
{“num”: “3”}
]
How can I get 3 and add it to 2? In short, how can I get the sum of the last 2 elements in an object?
Why not get the length of the $scope.sample by
$scope.sample.forEach(function(value,key){
// Add element 3 to element 2
var sum = 0;
if(key > 0){
sum = value.num + sum
}
console.log(sum)
})
But I think $scope.sample[index] should work since first element start from index 0
2nd and 3rd element should be $scope.sample[1].num + $scope.sample[2].num
thanks but what if the user adds new element:
New input: 0
$scope.sample =[
{“num” : “1”},
{“num”: “2”},
{“num”: “3”},
{“num”: “0”}
]
Answer: 3 (0+3)
Then remove the if key
var sum = 0;
$scope.sample.forEach(function(value,key){
sum = value.num + sum
console.log(sum)
})