I have an array of javascript objects and I am trying to get an array of all unique values for a specific property in each object. I tried to do this using reduce(), my example code is below, but it results in an error that it “Cannot read properties of undefined (reading ‘includes’)” even though I provided an initial value of an empty array. The intended result is an array with
['New York', 'San Francisco', 'Chicago', 'Los Angeles']
The end goal is to create a bar graph with the cities on the X-axis and the calculated average wage for each city on the Y-axis, so I need the unique list of cities. Is there a way to avoid this error, or a better way to do this altogether?
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);
}
}, []);