Remove duplicate values from a javascript vector, without the 'filter' function? [duplicate]

0

Hello, how are you? I'm trying to develop a function in javascript that gets an array of integers, and removes from the array only the repeated terms, I know there are pre-determined functions for this, but I'm testing developing develop in a more "handy" way, could they help me? I'm having some difficulty.

follow what I tested:

  var array_teste = [4, 1, 2, 2, 3, 4, 5, 5, 7, 8, 8, 15];//array de teste para a função
function remove_repetidos(arr) {
    for (var i = 0; i < arr.length; i++) {
        var teste = arr[i]; 
        console.log(teste);
        for (var j = 1; i < arr.length; j++) {
            if (arr[j] == teste){
                arr.splice(j, 1);
            };
        };
    };
}
console.log(array_teste);
remove_repetidos(array_teste);
console.log(array_teste);
    
asked by anonymous 14.11.2018 / 17:41

1 answer

1

I just saw the error you made, you created an infinite loop, in the second for you compared i instead of j , replace:

for (var j = 1; i < arr.length; j++) {

By:

for (var j = 1; j < arr.length; j++) {

My old response, if you'd like to take it into account.

I've used pretty much the same logic as you

let array_teste = [4, 1, 2, 2, 3, 4, 5, 5, 7, 8, 8, 15]

const remove_repetidos = (arr) => {
  let copiaArr = arr

  arr.forEach((elemento, index) => {
    if (elemento === copiaArr[index]) {
      arr.splice(index, 1)
    }
  })
}

remove_repetidos(array_teste)
console.log(array_teste)

The difference was that I used forEach , but you can replace it with a for , if you want.

Using the same codebase you would do it like this:

let array_teste = [4, 1, 2, 2, 3, 4, 5, 5, 7, 8, 8, 15] // array de teste para a função

function remove_repetidos(arr) {
  let copiaArr = arr

  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] === copiaArr[j]) {
        arr.splice(j, 1)
      }
    }
  }
}

console.log(array_teste);
remove_repetidos(array_teste);
console.log(array_teste);
    
14.11.2018 / 17:54