线段数组的唯一性

huangapple go评论69阅读模式
英文:

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 =&gt; {
  const isDuplicate = result.find(dp =&gt; {
    if (el.length !== dp.length)
      return false;
    return (el.length === 2) ?
      el[0][0] === dp[0][0] &amp;&amp; el[0][1] === dp[0][1] :
      el[0][0] === dp[0][0];

  });
  if (!isDuplicate) 
    result.push(el);
  
});

console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月27日 15:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577984.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定