-1
let input segment_arr=[ [[1,4],[4,5]  , [[5,6],[7,8]] , [[9,6],[7,8]] ,  [[1,4],[4,5]] , [[10,6],[7,8]] ]
 output_segment_arr=[ [[1,4],[4,5]] , [[5,6],[7,8]] , [[9,6],[7,8]] , [[10,6],[7,8]] ]

In my segment array, , the elements are in the form of [ [x1,y1] , [x2,y2] ] which represents 2 points that form a segment. May I know how to find the unique of this segment array so that it removes all the duplicates?

I will really appreciate an help I can get :)

James Tan
  • 15
  • 4
  • Does this answer your question? [How to get distinct values from an array of objects in JavaScript?](https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript) – Paddy Mar 24 '23 at 08:43
  • @Paddy, hi sir, I tried the code from the post to fit my example which is const data = [ [ [[1,4],[4,5] , [[5,6],[7,8]] , [[9,6],[7,8]] , [[1,4],[4,5]] , [[10,6],[7,8]] ] ]; const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B'] – James Tan Mar 24 '23 at 08:46
  • @Paddy, but it does not work, unfortunately :) – James Tan Mar 24 '23 at 08:47
  • Possibly this might be a better option as a duplicte target: https://stackoverflow.com/questions/46083783/javascript-find-and-remove-duplicates-conditionally – Paddy Mar 24 '23 at 09:57

1 Answers1

0

You could filter the data by using some closures, one over the Set and another to use a normalized value for the set, in this case a simple string.

const
    points = [[[1, 4], [4, 5]], [[5, 6], [7, 8]], [[9, 6], [7, 8]], [[1, 4], [4, 5]], [[10, 6], [7, 8]]],
    unique = points.filter((s => p => (v => !s.has(v) && s.add(v))(p.toString()))(new Set));

console.log(unique);

Bonus: Getting indices of unique pairsby using an index and get the point of the points array.

const
    points = [[[1, 4], [4, 5]], [[5, 6], [7, 8]], [[9, 6], [7, 8]], [[1, 4], [4, 5]], [[10, 6], [7, 8]]],
    unique = [...points.keys()].filter((s => i => (v => !s.has(v) && s.add(v))(points[i].toString()))(new Set));

console.log(unique);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Hi Nina, I really like your code, may i ask if I were to find the position index of all the unique elements in the points array, how am I suppose to do that :) ? – James Tan Mar 25 '23 at 11:44