Set only adds 1 copy of an array and I'm not sure why it doesn't keep adding other copies.
The function below takes in an array of trips with the travelers id and another array containing the travelers' ids and names. In this chunk of code,
if(item.type === type){
store.add(...item.travelers);
}
I expected that 123,456 and 789 will be added to the set. However, only 123 and 456 are added. Why doesn't the Set add in the second copy (which would be 456 and 789)?
const travelers = [
{
id: 123,
name: 'John'
},
{
id: 456,
name: 'Raymond'
},
{
id: 789,
name: 'Mary'
},
];
const trip = [
{
type: 'car',
travelers: [123, 456]
},
{
type: 'flight',
travelers: []
},
{
type: 'car',
travelers: [456, 789]
},
];
function determinePeopleForEachTripType(arr, travelers, type){
const result = [];
let store = new Set();
for(let i = 0; i< arr.length; i++){
let item = arr[i];
if(item.type === type){
store.add(...item.travelers);
}
}
store.forEach(eachStore =>{
for(let j = 0; j< travelers.length; j++){
if(eachStore === travelers[j].id){
result.push(travelers[j].name)
}
}
})
return result;
}
determinePeopleForEachTripType(trip, travelers, 'car');
Expected result: Set contains [123, 456, 789]. But actual output is Set contains [123, 456]. What are some possible ways to fix this code?