如何在 Ionic 2 中添加两个数组数据

How to add two arrays data in Ionic 2

我是 Ionic 2 的初学者。我想根据它们的位置添加到数组元素。 例如:我有 2 个数组 .

  1. lables:[Lillium,Gerbera,Gerbera,Lillium,Rose,Rose]

  2. Data : [10, 20, 10, 30, 20,10]

现在我想从标签[]中删除冗余并从数据[]中添加它们的值

我的最终数组应该是

labels: [Lillium,Gerbera,Rose]

data : [40,30,30]

我从 Json 中提取了这种类型的数据:

 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);

试试这个:

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);

根据您的评论,事情似乎可以做得容易得多

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);