2017-02-21 114 views
0

我遇到了一個奇怪的故障。我有一些代碼,我通過一組數組運行,抓取一堆城市名稱並將它們連接在一起。我需要從完成的列表中刪除重複項。這應該很簡單。使用計數來確定哪個城市有多個實例,然後拼接出來。我返回的數組沒有出來,雖然我不知道爲什麼。任何人都可以發現我做錯了什麼嗎?奇怪的打嗝從陣列中刪除重複項

const input = [ 
{ 
    name: "ACH2000", 
    year: 2005, 
    cities: ['Chicago', 'New York', 'Ames', 'Columbus'], 
    ages: [12, 32, 2, 51] 
}, 
{ 
    name: "FXG3000", 
    year: 2008, 
    cities: ['Chicago', 'Joliet', 'Plymouth', 'Dallas'], 
    ages: [12, 32, 2, 51] 
}, 
{ 
    name: "GTG1234", 
    year: 2012, 
    cities: ['Indy', 'Tampa', 'Houston', 'Dallas'], 
    ages: [12, 32, 2, 51] 
} 
]; 

function getUniqueCities(data){ 
    let citiesInArray = data.map(function(item){ return item.cities }); 
    let concatCities = [].concat.apply([], citiesInArray); 
    let count = {}; 
    for(let i = 0; i< concatCities.length; i++) { 
     let num = concatCities[i]; 
     count[num] = count[num] ? count[num]+1 : 1; 
     if(count[num] > 1){ 
     console.log('bad',num); 
     concatCities.splice(num, 1); 
     } else { 
     console.log('good',num); 
     } 
    } 
    console.log(count); 
    console.log(concatCities); 
} 

getUniqueCities(input); 
+2

您是否確實需要知道哪些城市不止一次出現過,或者僅僅返回沒有重複的列表就足夠了?無論如何,想想你的'.splicing()'out ... – nnnnnn

+0

這是返回的數組之後,數組中的項的索引會發生什麼? 'console.log(concatCities)'給出了獨特的城市? –

+0

@nnnnnn只是一個沒有重複的列表。我認爲你對這些指責有點意見。我認爲將它們拼接出來是造成我的問題的原因。 –

回答

2

,你可以嘗試這樣的事情

var input = [ 
    { 
     name: "ACH2000", 
     year: 2005, 
     cities: ['Chicago', 'New York', 'Ames', 'Columbus'], 
     ages: [12, 32, 2, 51] 
    }, 
    { 
     name: "FXG3000", 
     year: 2008, 
     cities: ['Chicago', 'Joliet', 'Plymouth', 'Dallas'], 
     ages: [12, 32, 2, 51] 
    }, 
    { 
     name: "GTG1234", 
     year: 2012, 
     cities: ['Indy', 'Tampa', 'Houston', 'Dallas'], 
     ages: [12, 32, 2, 51] 
    } 
]; 

var citiesStats = {}; 

input.forEach(data => 
    data.cities.forEach(city => { 
     if (!citiesStats[city]) { 
      citiesStats[city] = 0; 
     } 
     ++citiesStats[city]; 
    }) 
); 

var cities = Object.keys(citiesStats); 

// ["Chicago", "New York", "Ames", "Columbus", "Joliet", "Plymouth", "Dallas", "Indy", "Tampa", "Houston"] 
console.log(cities); 
// {"Chicago":2,"New York":1,"Ames":1,"Columbus":1,"Joliet":1,"Plymouth":1,"Dallas":2,"Indy":1,"Tampa":1,"Houston":1} 
console.log(citiesStats); 
+0

請注意,如果你所關心的是最終的無重複列表,那麼內部循環可以包含一行一行'citiesStats [city] = 0'(或= true或其他 - 值無關緊要)。 – nnnnnn

1

由於nnnnnn建議拼接循環內的陣列中,在搞亂了指數。

如果你可以使用Set,這裏是一個解決方案:

Array.from(new Set(concatCities)) 

這裏是fiddle的鏈接。