如何从javascript中的对象数组中删除重复的数据值?

问题描述 投票:1回答:2

我希望能够使用数组方法或其他任何形式的JavaScript处理而无需任何外部javascript库,以便遍历多维数组并删除任何重复的值。下面是一个示例:

var places = [{
    "category": "other",
    "title": "harry University",
    "value": 4788,
    "id": "1"
  },
  {
    "category": "traveling",
    "title": "tommy University",
    "value": 5460,
    "id": "2"
  },
  {
    "category": "education",
    "title": "jerry University",
    "value": 7853456,
    "id": "3"
  },
  {
    "category": "business",
    "title": "Charlie University",
    "value": 6779589,
    "id": "4"
  },
  {
    "category": "business",
    "title": "NYU",
    "value": 0117824,
    "id": "5"
  }
];

我尝试使用array.filter删除重复的category值,但是我采用的方法不起作用。

这是我的代码

places = places.map(JSON.stringify).reverse()
  .filter(function(item, index, places) {
    return places.indexOf(item, index + 1) === -1;
  })
  .reverse().map(JSON.parse)
console.log(places)

上面的方法不起作用,因为它在整个数组上运行,因此数据不会更改。

[当我使用underscore.js之类的库时,它们有一种有效的方法

let newPlaces = [];
_.each(_.uniq(_.pluck(places, "category")), function(category) {
  newPlaces.push(_.findWhere(places, {
    category: category
  }));
});
console.log(newPlaces);

但是我希望能够使用.filter或其他香草JavaScript方法。

javascript arrays underscore.js array-filter
2个回答
1
投票

您的示例不是多维数组。但是只是对象的规则数组。多维数组将类似于let a = [[1],[1]];,它是数组的数组。无论如何,您是否要删除所有已经出现过类别的对象(数组中的项目)。您可以根据需要使用Vanilla Javascript过滤器方法执行此操作。您只需要使用一个对象来计数该对象是否曾出现过。这是一个简单的方法

function removeDuplicates(arrToBeFiltered, keyToMatch){
  let dups = {};
  return arrToBeFiltered.filter(function(item){ 
    if(item[keyToMatch] in dups){return false;} 
    else {
        dups[item[keyToMatch]] = true; return true;
    }}); 
}
places = removeDuplicates(places,'category');

0
投票

简单的循环。只需使用数组和字符串过滤器调用DeDupPlaces

const DeDupPlaces = (arrToBefiltered, filter) => {
  const seen = [];
  const result = [];
  for (let i = 0; i < arrToBefiltered.length; i++) {
    const filterValue = arrToBefiltered[i][filter];

    if(!seen.includes(filterValue)){
        seen.push(filterValue);
        result.push(arrToBefiltered[i]);
    }
  }
  return result;
}
DeDupPlaces(places, 'category');

JS Fiddle with your example

© www.soinside.com 2019 - 2024. All rights reserved.