2 回答

TA貢獻1780條經驗 獲得超5個贊
您基本上是按州對城市進行分組。首先,array.map這不是解決此問題的正確方法,因為當您分組時,輸入項的編號可能與輸出項的編號不匹配。array.reduce是更好的選擇。
let newCityStateObject = cities.reduce((acc, item, index) => {
if (item) {
// this object has state as key, and the desired output array’s item as value
const object = acc.obj;
// if state not found, create new record
if (object[item.state] === undefined) {
const record = { name: item.state, cities: [] }
object[item.state] = record;
acc.array.push(record);
}
const record = object[item.state];
record.cities.push(item.city);
}
return acc;
}, { obj: {}, array: [] }).array;

TA貢獻1765條經驗 獲得超5個贊
這是另一種考慮方法:
let newCityStateObject = () => {
const statesArr = Array.from(cities, (item) => item.state);
// Remove state duplications
const filteredStates = [...new Set(statesArr)];
// Initializing the name and cities object and array
let result = filteredStates.map((item) => {
return { name: item, cities: [] };
});
// For each cite item, fetch the city to its corresponding result by state
cities.forEach((item) =>
result
.find((element) => element.name === item.state)
.cities.push(item.city)
);
return result;
}
添加回答
舉報