简体   繁体   English

JavaScript 中如何检查两个对象的匹配数据是否很少

[英]How to check whether two Objects has few of the matching data in JavaScript

I have data like this:我有这样的数据:

Array = [
  { 0: { Id: 18, Time: 3 } },
  { 1: { Id: 5, Time: 7 } },
  { 2: { Id: 18, Time: 10 } },
  { 3: { Id: 2, Time: 9 } },
];

As you can see Object 0 & Object 2 has same Id.如您所见, Object 0Object 2具有相同的 ID。 I want to perform an operation which will check whether any of the Objects has same Id in it and return true or false.我想执行一个操作,该操作将检查是否有任何对象具有相同的 Id 并返回 true 或 false。

The below code might help.下面的代码可能会有所帮助。

 function getMatch(array) { var idArray = array.map(a => a.Id); return idArray.some((a, index) => idArray.indexOf(a) !== index); } var arr = [ { Id: 18, Time: 3 }, { Id: 5, Time: 7 }, { Id: 18, Time: 10 }, { Id: 2, Time: 9 } ]; console.log(getMatch(arr));

You can map your array of objects its entries, and then map the entires to its Id to get an array of Ids.您可以将对象数组映射到其条目,然后将整个对象映射到其Id以获取Id数组。 You can put this array of ids into a set to remove duplicates and compare it with the length of the array to check if an Id was removed when creating the set.您可以将这个 id 数组放入一个集合中以删除重复项,并将其与数组的长度进行比较,以检查创建集合时是否删除了一个Id

 const arr = [{ 0: { Id: 18, Time: 3 } }, { 1: { Id: 5, Time: 7 } }, { 2: { Id: 18, Time: 10 } }, { 3: { Id: 2, Time: 9 } }]; const ids = arr.map(Object.values).map(([{Id}]) => Id); const hasSameId = ids.length !== new Set(ids).size; console.log(hasSameId);

Use this function which will tell same id exist in your array.使用这个函数会告诉你的数组中存在相同的 id。

 SameIdMatch() { let idList = []; for (let i = 0; i < Array.length; i++) { if(idList.indexOf(Array[i].Id) === -1) { idList.push(Array[i].Id); return true; } else { return false; } } }

Try this one liner.试试这个衬里。

 const input = [ { 0: { Id: 18, Time: 3 } }, { 1: { Id: 5, Time: 7 } }, { 2: { Id: 18, Time: 10 } }, { 3: { Id: 2, Time: 9 } } ]; const hasDuplicate = input.length !== [...new Set(input.map((item, index) => item[index].Id))].length; console.log(hasDuplicate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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