奇怪的打嗝从数组中删除重复项

时间:2017-02-21 06:32:16

标签: javascript arrays splice

我遇到了一个奇怪的故障。我有一些代码,我通过一组数组运行,抓住一堆城市名称并将它们连接在一起。我需要从完成的列表中删除重复项。这应该很简单。使用计数来确定哪个城市有多个实例,然后将它们拼接出来。我的返回阵列虽然没有出现,但我不确定为什么。谁能发现我做错了什么?

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

由于nnnnnn建议在循环内部进行拼接会弄乱数组中的索引。

如果你可以使用Set,这是一个解决方案:

Array.from(new Set(concatCities))

以下是指向fiddle的链接。