javascript - 如何快速比较数组中的所有元素

标签 javascript html arrays object html5-canvas

我有一个包含 100 个元素的字符串,该数组有 100 个对象。这些对象具有 X 和 y 值。我想找到具有相同 X 和 y 值的元素。我怎样才能做到这一点?

 for (var i = 0; i < circleArray.length; ++i) {
                for (var j = 1; j < circleArray.length; ++j)
                    if (circleArray[i].x == circleArray[j].x && circleArray[i].y == circleArray[j].y) {
                        console.log("mission completed");
                    }
            }

我按照上面的方法进行操作,但它会消耗大量性能并且运行速度非常慢。

所有代码:https://codepen.io/tolgaand/pen/PoYzaKP

最佳答案

我们可以使用Set根据xy两个属性判断是否遇到重复元素,如果是重复我们将其添加到 dup 数组中:

const circleArray = [{x: 100, y: 200, c: 30}, {x:50, y:40, c:56}, 
                     {x:23, y:78, c:90}, {x:50, y:40, c:78}, 
                     {x:23, y:78, c:98}, {x:2, y:378, c:90}, 
                     {x:237, y:8, c:10}];
                     
//To get the duplicate objects
const seen = new Set();
const dup = circleArray.reduce((acc, obj) => {
  //if size is same, the object is a duplicate based on x and y props
  if(seen.size === seen.add(obj.x + "|" + obj.y).size){ 
    acc.push(obj);
  }
return acc;
}, []);
console.log(dup);

要删除重复项,我们可以使用Array.prototype.filter根据xy将重复的对象过滤到新数组中> 属性:

//To remove duplicates 
const circleArray = [{x: 100, y: 200, c: 30}, {x:50, y:40, c:56}, 
                         {x:23, y:78, c:90}, {x:50, y:40, c:78}, 
                         {x:23, y:78, c:98}, {x:2, y:378, c:90}, 
                         {x:237, y:8, c:10}];
                         
const seen = new Set();
const filtered = circleArray.filter((obj) => {
 //if size is same, the object is a duplicate based on x and y props
 return seen.size !== seen.add(obj.x + "|" + obj.y).size
});
console.log(filtered);

关于javascript - 如何快速比较数组中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542756/

相关文章:

javascript - 使用 Bootstrap 模式的 Youtube 视频

javascript - 如何使用 DOM 更改表格内单行的背景颜色

c# - ASP.NET 中的动态表单生成

java - 如何从 HTML/JS 和 android 调用 Java 服务器端方法?

javascript - 相对布局,移动版显示不正确.. HTML/CSS

arrays - Flatten 在直接调用和在方法中调用时的工作方式不同

c - 使用 stdlib.c 中的 qsort() 根据每个 *char 中的第三个字母对 C 中的字符串数组进行排序

php - 如何在 PHP 中将这个简单的文本 block 解析为多维数组?

PHP session_start() 用法

html - Bootstrap 3 图像对齐问题