如何使用JavaScript/Angular对手机列表去重并统计各型号数量?
Angular实现手机列表去重与数量统计展示
没问题,我来帮你搞定这个需求!我们可以通过组件内数据预处理 + ngFor渲染的方式实现,步骤很清晰:
1. 在组件中完成数据统计与去重
首先我们需要把原始的data数组转换成按品牌+型号分组、带数量统计的新数组。这里用JavaScript的reduce方法就能高效实现:
import { Component } from '@angular/core'; @Component({ selector: 'app-phone-list', templateUrl: './phone-list.component.html', styleUrls: ['./phone-list.component.css'] }) export class PhoneListComponent { // 原始数据 data = [ { id: 1, type: 'smartphone', details: [{ brand: 'Samsung', model: 'Galaxy A5' }] }, { id: 2, type: 'smartphone', details: [{ brand: 'iPhone', model: '6 plus' }] }, { id: 3, type: 'smartphone', details: [{ brand: 'Samsung', model: 'Galaxy A5' }] }, { id: 4, type: 'smartphone', details: [{ brand: 'iPhone', model: '7 plus' }] }, { id: 5, type: 'phone', details: [{ brand: 'Nokia', model: '3310' }] }, { id: 6, type: 'smartphone', details: [{ brand: 'Samsung', model: 'Galaxy A5' }] }, { id: 7, type: 'smartphone', details: [{ brand: 'iPhone', model: '6 plus' }] } ]; // 统计后的结果数组,供模板渲染 phoneStats: { brand: string; model: string; count: number }[] = []; ngOnInit() { // 使用reduce分组统计 const statsMap = this.data.reduce((acc, item) => { // 取出当前项的品牌和型号(注意details是数组,这里取第一个元素) const { brand, model } = item.details[0]; // 用品牌+型号作为唯一键 const key = `${brand}-${model}`; if (!acc[key]) { // 如果该组合不存在,初始化统计项 acc[key] = { brand, model, count: 1 }; } else { // 如果已存在,数量+1 acc[key].count++; } return acc; }, {} as Record<string, { brand: string; model: string; count: number }>); // 把对象转成数组,供ngFor遍历 this.phoneStats = Object.values(statsMap); } }
2. 用ngFor在模板中渲染结果
接下来在组件的HTML模板里,直接遍历我们处理好的phoneStats数组就行:
<div *ngFor="let stat of phoneStats"> 手机:{{ stat.brand }},型号:{{ stat.model }},总数:{{ stat.count }} </div>
逻辑说明
- 我们用
reduce遍历原始数据,以品牌-型号作为唯一标识键,避免重复统计; - 每遇到一个新的品牌型号组合就初始化统计项,遇到已存在的就累加数量;
- 最后用
Object.values把统计后的对象转换成数组,这样就能直接用*ngFor遍历渲染了; - 如果你的
details数组可能有多个元素,可以根据实际需求调整取值逻辑(比如遍历details数组或者取特定元素)。
这样就能得到你预期的展示效果啦!
内容的提问来源于stack exchange,提问作者SED
相关产品推荐
相关产品推荐

