在对象数组中查找重复元素

时间:2018-03-15 20:52:04

标签: javascript reactjs

我有几个JSON对象数组。我需要迭代数组,如果有两个或多个具有相同userId值的元素,则返回true。

[{
"name":"John",
"age":30,
"userId": 5,
}],

[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],

[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]

到目前为止,这是我的方法,我正在遍历数组并检查是否存在具有506 userId存在的用户。

isPostedMultiple = (data) => {
 for (let j = 0; j < data.length; j++) {
   if (data[j].UserId == '506') {
    console.log('506 data :', data[j]);
   } else {
    console.log('not 506 data'); 
   }
 }
}

5 个答案:

答案 0 :(得分:3)

首先,您提供的对象是错误的。说得对。来到这个问题, 您可以结合使用Array.prototype.someArray.prototype.filter

data.some(
  (el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);

检查是否存在多个符合特定条件的元素。

&#13;
&#13;
var data = [{
    "name": "John",
    "age": 30,
    "userId": 5,
  },
  {
    "name": "Benjamin",
    "age": 17,
    "userId": 5,
  },
  {
    "name": "Johnatan",
    "age": 35,
    "userId": 10,
  }
];

var result = data.some(
  (el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);

console.log(result)
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用数组扩展语法合并数组,而不是将reducefilter方法一起使用

const mergedArrays = [...arr1, ...arr2, ...arr3];
const isDublicated = mergedArrays.reduce(
  (acc, item) => acc || mergedArrays.filter(user => user.userId === item.userId) > 1,
  false
);

答案 2 :(得分:0)

要获得预期的结果,请使用以下选项使用filter和findIndex迭代每个数组并比较userId

&#13;
&#13;
var x = [[{
"name":"John",
"age":30,
"userId": 5,
}],

[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],

[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]]

x = x.filter((v, i, self) =>
  i === self.findIndex((y) => (
     y[0].userId === v[0].userId
  ))
)


console.log(x);
&#13;
&#13;
&#13;

代码示例 - https://codepen.io/nagasai/pen/wmWqdY?editors=1011

答案 3 :(得分:0)

var jsonObj1 = [{
"name":"John",
"age":30,
"userId": 5
},

{
"name":"Benjamin",
"age":17,
"userId": 5
},

{
"name":"Johnatan",
"age":35,
"userId": 10
}];

var jsonObj2 = [{
"name":"John",
"age":30,
"userId": 5
},

{
"name":"Benjamin",
"age":17,
"userId": 15
},

{
"name":"Johnatan",
"age":35,
"userId": 10
}];

var logger = document.getElementById('logger');
logger.innerHTML = "";

function checkForDupIds(jsonObj, headerStr) {
  var logger = document.getElementById('logger');
  var hasDups = [];
  var items = [];
  for(var a=0;a<jsonObj.length;a++) {
    if (items.includes(jsonObj[a].userId)) {
      hasDups.push(jsonObj[a].userId);
    } else {
      items.push(jsonObj[a].userId);
    }
  }
  logger.innerHTML += "<h1>" + headerStr + "</h1>";
  for(var b=0;b<hasDups.length;b++) {
    logger.innerHTML += "<div>" + hasDups[b] + "</div>\n";
    console.log(hasDups[b]);
  }
  if (hasDups.length === 0) {
    logger.innerHTML += "<div>No Duplicates Found</div>\n";
  }
}

checkForDupIds(jsonObj1, "jsonObj1");
checkForDupIds(jsonObj2, "jsonObj2");
<html>
<body>
<div id='logger'></div>
</body>
</html>

答案 4 :(得分:0)

您可以遍历数组并计算每个userId值出现的次数。如果你得到2的任何值,停止并返回false(或其他一些合适的值)。

shouldn't be associated with any node允许循环遍历数组,直到条件为真,因此它只在源上循环一次。 OP中的数据无效,我已将其修改为对象数组。

&#13;
&#13;
var data = [{
"name":"John",
"age":30,
"userId": 5
},
{
"name":"Benjamin",
"age":17,
"userId": 5
},
{
"name":"Johnatan",
"age":35,
"userId": 10
}]

function hasDupIDs(data) {
  // Store for userId values
  var ids = {};
  // Loop over values until condition returns true
  return data.some(function(x) {
    // If haven't seen this id before, add to ids
    if (!ids.hasOwnProperty(x.userId)) ids[x.userId] = 0;
    // Increment count
    ids[x.userId]++;
    // Return true if second instance
    return ids[x.userId] > 1;
  });
}

console.log(hasDupIDs(data));
&#13;
&#13;
&#13;

如果您想要更简洁的代码,可以使用:

&#13;
&#13;
var data = [
  {"name":"John","age":30,"userId": 5},
  {"name":"Benjamin","age":17,"userId": 5},
  {"name":"Johnatan","age":35,"userId": 10}];

function hasDupIDs(data) {
  var ids = {};
  return data.some(x => {
    ids[x.userId] || (ids[x.userId] = 0);
    return ++ids[x.userId] > 1;
  });
}

console.log(hasDupIDs(data));
&#13;
&#13;
&#13;