我是 Ionic 2 的初学者。我想根据它们的位置添加到数组元素。 例如:我有 2 个数组。
- 数据 : [10, 20, 10,
标签:[镰
子,非洲菊,非洲菊,百合菊,玫瑰,玫瑰]30, 20,10]
现在我想从标签 [] 中删除冗余,并希望从 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);