我有一个包含 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");
}
}
我按照上面的方法进行操作,但它会消耗大量性能并且运行速度非常慢。
最佳答案
我们可以使用Set
根据x
和y
两个属性判断是否遇到重复元素,如果是重复我们将其添加到 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
根据x
和y
将重复的对象过滤到新数组中> 属性:
//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/