I have a Javascript array that contains other arrays inside it. My question would be how to remove an array if it appears repeated in the array that contains them. So:
Input:
[["#FFF", "Blanco"], ["#000", "Negro"], ["#000", "Negro"]]
Output
[["#FFF", "Blanco"], ["#000", "Negro"]]
Clarification : To be considered repeated it has to be more than once in the array, and what I want is that this repeated array only remains once. And yes, the order influences, that is to say: ["Black", "#000"]
and they ["#000","Black"]
would be different elements.
What I've been trying : I've tried using the object Set
but realized that it doesn't work with Arrays, it only works with elements inside an Array. filter
I also used the and methods forEach
but got nothing.
you can combine the use of
forEach
with thefindIndex
and take advantage of the optional parameters of both ( index for this case ) the findIndex cuts in the return of a true passed by condition but for the case before returning the true you evaluate in a condition if the elements are equal Note that they are being evaluated as strings and also that they are not being evaluated as wellindice!=index
. I hope it works for you, greetings!Clarification
It will only clean if it is repeated once with
findIndex
it, if you are looking for all the repeated ones to be eliminated, you could easily call againforeach
and remove thereturn
An array cannot be compared for equality with another.
["a"] == ["a"]
always returnsfalse
because they are different instances . The best way is to use a loop that compares all the elements (amount, type and value)... But I'm not going to answer with the best way.This shape is a bit rustic and clearly won't be the best performer, but I like to use it for this case.
An alternative can be
you can use a Set to do the search, passing each element to a String and saving them in the Set, being in a String it will be saved only once.
If each element of the array when looking for it in the Set does not exist, it is because it is the first incidence, if in the other iterations you find it, it is because the object that is in the current index was already found, for which it is repeated and will not form part of the result array.