Reputation: 520
I'm trying to multiply the last children of an array by a variable number for use in a chart but I can't get the multiplier to work.
Here's my code:
var data = [12, 19, 3, 5, 2, 3,12,43,60,78,98,130];
data.slice(-6, 13)*1.2;
Upvotes: 0
Views: 107
Reputation: 1268
data.slice(-6, 13)
- gives you an array, you can't multiply an array. You need to loop through values and multiply them.
var data = [12, 19, 3, 5, 2, 3,12,43,60,78,98,130];
var dataToMultiply = data.slice(-6, 13);
var multipliedData = [];
dataToMultiply.forEach(function(element) {
multipliedData.push(element * 1.2);
});
console.log(multipliedData);
Upvotes: 3
Reputation: 5564
if you want to get the following values multiplied by 1.2,
[12, 43, 60, 78, 98, 130]
You can use the Array#map
method :
var data = [12, 19, 3, 5, 2, 3,12,43,60,78,98,130];
data.slice(-6, 13).map(function(el) { return el * 1.2;})
// => [14.399999999999999, 51.6, 72, 93.6, 117.6, 156]
and if you want to keep them in the array, you can do the following :
var data = [12, 19, 3, 5, 2, 3,12,43,60,78,98,130];
data.map(function(el, i) { return i >= 6 ? el * 1.2 : el});
Hope it helps,
Best regards
Upvotes: 3