I am trying to write a function in JavaScript to get the unique values of an array, but my code does not work correctly. I know there are other better and simpler ways to do it, but I don't understand why my code doesn't work and I want to understand it.
The function has two for-loops, if the outer index and the inner index are distinct and the value of these index positions are the same, the position of the inner index is pushed to another array. When the inner for-loop ends, the indexes anotated in the other array are replaced in the original array by null values to be removed later.
the input is: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
but the output is: 1 2 null null null null 4 4 4 4 5 5 5 5 5
I'don't know what is going wrong, can someone help me?
function uniqueArrayValues(vector) {
var indexRepeated = [];
for (let i in vector) {
for (let j in vector) {
if (vector[i] == vector[j] && i != j && j != null && i != null && i < j ) {
indexRepeated.push(j);
}
}
for (let i in indexRepeated) {
if (vector[indexRepeated[i]] != null) {
vector.splice(vector[indexRepeated[i]], 1, null);
}
}
}
}
Array.from(new Set([1,1,2,3]))
– Carpogonium