简体   繁体   中英

Weird hiccup removing duplicates from an array

I'm running into a weird glitch. I have a bit of code where I'm running thru an array of arrays, grabbing a bunch of city names and concatenating them all together. I need to remove the duplicates from the finished list. This should be pretty simple. Use a count to figure out which city has more than one instance and then splice them out. My returned array isn't coming out right though and I'm not sure why. Can anyone spot what I'm doing wrong?

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

you can try something like this

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

As nnnnnn suggested splicing inside the loop is messing up the indices in the array.

If you can use Set , here is a solution:

Array.from(new Set(concatCities))

Here is a link to fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM