我想在一个数组(相同的水果)中找到similair元素并计算总量,例如,我有以下列表:
val seekBarDrawable = ContextCompat.getDrawable(context, R.drawable.seek_bar_progress)
val seekBarDrawableLayerDrawable = seekBarDrawable as LayerDrawable
val ovalItem = seekBarDrawableLayerDrawable.findDrawableByLayerId(R.id.background) as GradientDrawable
ovalItem.colors = intArrayOf(Color.RED, Color.GREEN)
ovalItem.gradientType = GradientDrawable.LINEAR_GRADIENT
列表中不应包含数量不同的similair元素(水果),应该像这样:
let array = [
{
fruit: "Apple",
quantity: "2",
},
{
fruit: "Banane",
quantity: "1",
},
{
fruit: "Kiwi",
quantity: "5",
},
{
fruit: "Banane",
quantity: "2",
},
{
fruit: "Apple",
quantity: "6",
},
{
fruit: "Ananas",
quantity: "10",
},
{
fruit: "Apple",
quantity: "3",
}
];
我尝试使用过滤器indexOf来获得具有相同水果值的元素,但未成功。什么是正确的解决方案?
答案 0 :(得分:0)
这里有一段简短的代码可以满足您的需求,注释会详细说明。
const counts = {} // This will keep track of the counts of each fruit as key value pair
array.forEach(element => {
if(counts[element.fruit] !== undefined) { // This means that the current fruit have been found before
return counts[element.fruit] += Number(element.quantity); // Add the quantity of the current fruit element to the overall summation
}
// If the return statement above was not executed, it means that we are seeing the the fruit for the first time
counts[element.fruit] = Number(element.quantity);
// Initialize an entry for it in the summations object above, initally set to the current elements quantity
});
// Map the object to become an array again, and overwrite the original array with it if that's desired
array = Object.keys(counts).map(fruit => ({fruit, quantity: counts[fruit]}));