简体   繁体   中英

Javascript remove row from multidimensional array when elements are duplicated

I have the following array.

[{
  'firstname': 'John',
  'surname': 'Smith',
  'HouseNo': 'firtree farm'
}, {
  'firstname': 'Paul',
  'surname': 'Smith',
  'HouseNo': 'firtree farm'
}, {
  'firstname': 'John',
  'surname': 'Smith',
  'HouseNo': 'firtreefarm'
}, {
  'firstname': 'John',
  'surname': 'Smith',
  'HouseNo': 'firtree farmhouse'
}, {
  'firstname': 'Paul',
  'surname': 'Smith',
  'HouseNo': 'firtree farmhouse'
}, {
  'firstname': 'Paul',
  'surname': 'Smith',
  'HouseNo': 'FirTree farmhouse'
}]

I need to produce another array that contains no duplicates of element 'HouseNo' and just the element 'HouseNo. Also it need to be case insensitive.

ie.

[{
  'HouseNo': 'firtree farm'
}, {
  'HouseNo': 'firtreefarm'
}, {
  'HouseNo': 'firtree farmhouse'
}, {
  'HouseNo': 'FirTree farmhouse'
}]

The application is a returned set of address's based on a postcode search. I can then offer a filtered list of unique houseNo's they can choose form.

MrWarby

You can keep track of the already seen items in an object, and if you get an item which is not there in the seen , then push it to the result .

var seen = {};
var result = data.reduce(function(result, current) {
    if (!seen[current.HouseNo]) {
        seen[current.HouseNo] = true;
        result.push(current.HouseNo);
    }
    return result;
}, []);
console.log(result);

Output

[ 'firtree farm',
  'firtreefarm',
  'firtree farmhouse',
  'FirTree farmhouse' ]

If you want to maintain the object structure, then while pushing to the result, just create an object like this

result.push({HouseNo: current.HouseNo});

and the result would be

[ { HouseNo: 'firtree farm' },
  { HouseNo: 'firtreefarm' },
  { HouseNo: 'firtree farmhouse' },
  { HouseNo: 'FirTree farmhouse' } ]

If the Order of the data doesn't matter, then you can simply keep adding the HouseNo to an object and finally get the keys like this

var result = data.reduce(function(result, current) {
    result[current.HouseNo] = true;
    return result;
}, {});
console.log(Object.keys(result));

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