按属性javascript删除数组重复项

时间:2016-05-20 16:49:52

标签: javascript

我有一个对象列表:

   [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}]

我需要一种简单的方法来过滤掉与name属性相关的重复项,所以:

 [{name: "bob", age: "14"}, {name: "sue", age: "21"}]

似乎有相当多的数组重复删除问题,但不是基于属性的任何问题。它可以忽略所有其他字段。

5 个答案:

答案 0 :(得分:1)

迭代数组,将所有name值放在哈希中,并跳过name已经在哈希中的对象:

filterBy = function(ary, prop) {
  var seen = {};
  return ary.filter(function(item) {
    var key = item[prop];
    if(seen[key] === 1)
      return false;
    seen[key] = 1;
    return true;
  });
}

// 
a = [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}]

b = filterBy(a, 'name');

console.log(b);

ES6版本:

filterBy = function(ary, prop) {
  var seen = new Set();
  return ary.filter(item => !seen.has(item[prop]) && seen.add(item[prop]));
}

a = [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}]

b = filterBy(a, 'name');

console.log(b);

答案 1 :(得分:0)

您可以使用forEachthisArg param。

执行此操作

var data = [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}];
var result = [];

data.forEach(function(e) {
  if (!this[e.name]) {
    this[e.name] = e;
    result.push(this[e.name]);
  }
}, {});

console.log(result)

forEachmap()

var data = [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}], result =[];

data.forEach(function(e) {
  if(result.map(a => {return a.name}).indexOf(e.name) == -1 ) result.push(e);
});

console.log(result)

答案 2 :(得分:0)

您可以使用2 for循环执行此操作,如下所示。您所要做的就是保留一个结果数组,每次插入时都要检查名称属性是否相等。

function findDuplicate(){
  var array= [{name: "bob", age: "14"}, {name: "bob", age: "16"}, {name: "sue", age: "21"}];

  var result=[];
  for(x in array){
    var found=false;
    for(y in result){
      if(result[y].name.localeCompare(array[x].name)==0){
        found=true;
      }
    }
    if(!found){
      result.push(array[x]);
    }
  }
  console.log(result);
}

答案 3 :(得分:0)

如果已经过滤了相同的名称,您可以使用Array#filter_id对象进行标记。



this




答案 4 :(得分:0)

对于Q.中的直接比较,有一些 这里的答案很好。如果要提供自定义比较 可用于例如对象值,或使用 一个RegExp,然后看看以下内容。



var dedupwhen = function(fn, list){
    if(list[0] === undefined){
        return [];
    }
    // Join the first item to the remainder that has had the first
    // item filtered out (according to fn) and then been
    // deduplicated itself.
    return [list[0]].concat(dedupwhen(fn, list.slice(1).filter(function(item){
        return !fn(list[0], item);
    })));
};

var similarname = function(x,y){
    return RegExp('^' + x.name + '$', 'i').test(y.name);
};

var list = [
    {name: 'Sue', age: 44},
    {name: 'Bob', age: "14"},
    {name: 'bob', age: "16"},
    {name: 'sue', age: "21"}
];
console.log(dedupwhen(similarname, list));