我有一个Javascript对象数组,我试图获取每个对象特定属性的所有唯一值的数组。我尝试使用reduce()实现这个目标,我的示例代码如下,但是它会出现错误:"Cannot read properties of undefined (reading '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);
}
}, []);
reduce
函数没有返回任何内容。请注意,如果您还要进行过滤,则reduce
可能不是最佳方法。 - Dave Newton