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

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

关于javascript - 奇怪的打cup从阵列中删除重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42360225/

10-12 13:08