Remove duplicate values from a javascript array without the filter function?

Asked

Viewed 74 times

0

Hey, how you doing? I am trying to develop a javascript function that receives an array of integers, and removes from the array only the repeated terms, I know there are predetermined functions for this, but I am trying to develop more "manual" way, could you help me? I’m having some difficulty.

follows 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);
  • The second for has i < arr.length when it should be j < arr.length

  • You can use the reduce.

1 answer

1

I just saw the mistake you made, you created an endless loop in the second for you compared i instead of j, substitute:

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

For:

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

My old answer, if you want to take into account.

I 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 I used forEach, but you can replace it with a for, if you want.

Using the same code base as you:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.