skip to Main Content

I have array like this below

[[0,0,1],
[0,0,3]
[0,0,3]//duplicate
[0,1,3]
[1,0,0]
[1,2,1]
[1,2,1]//duplicate
[2,2,2]]

I want to make array like this below,

[[0,0,1],
[0,0,3]
[0,1,3]
[1,0,0]
[1,2,1]
[2,2,2]]

At first, I tried with this, but it returns []

 myarray = myarray.filter(
     (element,index,self) =>self.findIndex((e) => {
         e[0] == element[0] && 
         e[1] == element[1] && 
         e[2] == element[2] 
      }) === index 
 )

How can I make this work?

2

Answers


  1. I use .toString() on each array, remove duplicated strings then split them again.

    const arr = [
      [0, 0, 1],
      [0, 0, 3],
      [0, 0, 3], //duplicate
      [0, 1, 3],
      [1, 0, 0],
      [1, 2, 1],
      [1, 2, 1], //duplicate
      [2, 2, 2]
    ]
    const removedDuplicates = new Set(arr.map(a => a.toString()))
    const result = [...removedDuplicates].map(a => a.split(','))
    console.log(result)
    Login or Signup to reply.
  2. A safe method is to combine Set with JSON.stringify and .parse

    const uniqueArray = arr => Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
    
    
    const myArray = [
      [0, 0, 1],
      [0, 0, 3],
      [0, 0, 3], // duplicate
      [0, 1, 3],
      [1, 0, 0],
      [1, 2, 1],
      [1, 2, 1], // duplicate
      [2, 2, 2],
    ];
    
    
    console.log(uniqueArray(myArray));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search