gpt4 book ai didi

javascript - 如何在 Javascript 对象数组中查找特定键的所有唯一值?

转载 作者:行者123 更新时间:2023-12-01 23:01:28 24 4
gpt4 key购买 nike

我有一个 javascript 对象数组,我正在尝试获取每个对象中特定属性的所有唯一值的数组。我尝试使用 reduce() 执行此操作,下面是我的示例代码,但它会导致错误“无法读取未定义的属性(读取‘includes’)”,即使我提供了一个空数组的初始值。预期的结果是一个数组

['New York', 'San Francisco', 'Chicago', 'Los Angeles']

最终目标是创建一个条形图,其中 X 轴为城市,Y 轴为每个城市的计算平均工资,因此我需要唯一的城市列表。有没有办法避免这个错误,或者有更好的方法来完全做到这一点?

const employees= [
{id: 0, city: 'New York', wagePerHour: '15'},
{id: 1, city: 'San Francisco', wagePerHour: '18'},
{id: 2, city: 'New York', wagePerHour: '16'},
{id: 3, city: 'Chicago', wagePerHour: '14'},
{id: 4, city: 'Chicago', wagePerHour: '12'},
{id: 5, city: 'San Francisco', wagePerHour: '15'},
{id: 6, city: 'New York', wagePerHour: '18'},
{id: 7, city: 'Los Angeles', wagePerHour: '10'}
];
const cities = employees.reduce((foundValues, nextEmployee) => {
if(! foundValues.includes(nextEmployee.city)) {
foundValues.push(nextEmployee.city);
}
}, []);

最佳答案

一种更简单的方法是提取所有城市名称并使用 Set 函数构建一个唯一数组:

const employees = [{ id: 0, city: 'New York', wagePerHour: '15' }, { id: 1, city: 'San Francisco', wagePerHour: '18' }, { id: 2, city: 'New York', wagePerHour: '16' }, { id: 3, city: 'Chicago', wagePerHour: '14' }, {  id: 4, city: 'Chicago', wagePerHour: '12' }, { id: 5, city: 'San Francisco', wagePerHour: '15' }, {  id: 6, city: 'New York', wagePerHour: '18' }, { id: 7, city: 'Los Angeles', wagePerHour: '10' }]

let cities = [... new Set(employees.map(x=>x.city))];

console.log(cities);

关于javascript - 如何在 Javascript 对象数组中查找特定键的所有唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71740191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com