javascriptarraysunique-values

Get unique values of a Javascript array


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);
      }
    }
  }
}

Solution

  • You are almost there.

    splice() method's first parameter is the start index, the index at which to start changing the array.

    In your code, vector.splice(vector[indexRepeated[i]], 1, null); you are passing the value at that index in vector array instead of that index. That is the reason for unexpected output.

    Just change that line to vector.splice(indexRepeated[i], 1, null); and filter null values.

    Live Example:

    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(indexRepeated[i], 1, null);
          }
        }
      }
     
      return vector.filter(value => value !== null); // Can also use vector.filter(value => value);
    }
    
    var arr = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5];
    
    console.log(uniqueArrayValues(arr));

    Here are some other simpler ways to get unique values from an array.

    1) Using filter():

    var arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5];
    
    var unique = arr.filter((value, index, arr) => index === arr.indexOf(value));
    
    console.log(unique);

    2) Using Set():

    var arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5];
    
    var unique = [...new Set(arr)];
    
    console.log(unique);