英文:
Unique of Line Segments Array
问题
Unique Output: [ [[396.72, 241.07],[396.72, 241.07]], [[1,2],[2,1]], [[3,2],[9,1]] ]
英文:
let array= [ [[396.72, 241.07],[396.72, 241.07]], [[1,2]],[[2,1]] ,[[396.72, 241.07],[396.72, 241.07]], [[3,2],[9,1]] , [[2,1]],[[1,2]] ];
Unique Output: [ [[396.72, 241.07],[396.72, 241.07]], [[1,2],[2,1]], [[3,2],[9,1]] ]
For example, treat [[1,2]],[[2,1]] as a segment [[x1,y1],[x2,y2]] which has Point 1 and Point 2 .The points are interchangeable since if interchanged it will also form the same segment. May I ask how to find the unique of the array?
There is a solution on 2 dimensional array at here for Points or Coordinates, but its not exactly related to segment. Can anyone guide me on this matter ?
答案1
得分: 1
你需要使用 .find 方法来比较数组,如果不是重复的,则将数组推送到结果中,如下所示:
let array = [
[
[396.72, 241.07],
[396.72, 241.07]
],
[
[1, 2]
],
[
[2, 1]
],
[
[396.72, 241.07],
[396.72, 241.07]
],
[
[3, 2],
[9, 1]
],
[
[2, 1]
],
[
[1, 2]
]
];
const result = [];
array.forEach(el => {
const isDuplicate = result.find(dp => {
if (el.length !== dp.length)
return false;
return (el.length === 2) ?
el[0][0] === dp[0][0] && el[0][1] === dp[0][1] :
el[0][0] === dp[0][0];
});
if (!isDuplicate)
result.push(el);
});
console.log(result);
希望这有帮助。
英文:
You need to use .find and compare the array, if is not duplicate push the array into result like:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let array = [
[
[396.72, 241.07],
[396.72, 241.07]
],
[
[1, 2]
],
[
[2, 1]
],
[
[396.72, 241.07],
[396.72, 241.07]
],
[
[3, 2],
[9, 1]
],
[
[2, 1]
],
[
[1, 2]
]
];
const result = [];
array.forEach(el => {
const isDuplicate = result.find(dp => {
if (el.length !== dp.length)
return false;
return (el.length === 2) ?
el[0][0] === dp[0][0] && el[0][1] === dp[0][1] :
el[0][0] === dp[0][0];
});
if (!isDuplicate)
result.push(el);
});
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论