I am Beginner in Ionic 2. I want to add to array element as per their position. for Ex: i have 2 array .
lables:[Lillium,Gerbera,Gerbera,Lillium,Rose,Rose]
Data : [10, 20, 10, 30, 20,10]
Now I want to remove redundancy from labels[] and want to add their values from data[]
My final array should be
labels: [Lillium,Gerbera,Rose]
data : [40,30,30]
I have Extracted Data from Json this type:
var qp = []
for (var i of res.data) {
qp.push(i.quantity_produced);
console.log(res.data);
console.log(qp);
var name = []
for (var i of res.data) {
name.push(i.product);
var s= [new Set(name)];
console.log(res.data);
console.log(name);
Try this:
let labels = ['Lillium', 'Gerbera', 'Gerbera', 'Lillium', 'Rose', 'Rose'];
let Data = [10, 20, 10, 30, 20, 10];
//for each unique label....
let result = [...new Set(labels)]
//... get each occurence index ...
.map(value => labels.reduce((curr, next, index) => {
if (next == value)
curr.push(index);
return curr;
}, []))
//... and reducing each array of indexes using the Data array gives you the sums
.map(labelIndexes => labelIndexes.reduce((curr, next) => {
return curr + Data[next];
}, 0));
console.log(result);
Based on your comment seems that things can be done a lot easier
let data = [{product: 'Lillium',quantity_produced: 10}, {product: 'Gerbera',quantity_produced: 20},{product: 'Gerbera',quantity_produced: 10}, {product: 'Lillium',quantity_produced: 30}, {product: 'Rose',quantity_produced: 20}, {product: 'Rose',quantity_produced: 10}];
let result = data.reduce((curr, next) => {
curr[next.product] = (curr[next.product] || 0) + next.quantity_produced;
return curr;
}, {});
console.log(result);