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

Weird hiccup removing duplicates from an array

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

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);

你可以试试这个

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);

正如 所建议的那样,循环内的拼接会弄乱数组中的索引。

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

Array.from(new Set(concatCities))

这是link到fiddle