0

I need to check if 2 values in an array of inputs are the same, in order to remove the duplicates.

I have tried a single for loop which compares i

const input1 = document.querySelector("#a")
const input2 = document.querySelector("#b")
const unsafeInputs = [input1, input2]

function checkInputs() {
  for (let i = 0, j = unsafeInputs.length; i < j; i++) {
    if (unsafeInputs[i].value === unsafeInputs[j].value) {
      console.log("values are same")
      unsafeInputs[i].value = ""
    }
  }
}

input1.onchange = function() {
  checkInputs()
}
<input id="a">
<input id="b">

2 Answers2

1

You can use 2 for loops and check if any 2 inputs i and j (where i is not equal to j) have the same value. If they have the same value, you can clear the duplicate value from input j.

const input1 = document.querySelector("#a")
const input2 = document.querySelector("#b")
const input3 = document.querySelector("#c")
const unsafeInputs = [input1, input2, input3]

function checkInputs() {
  for (let i = 0; i < unsafeInputs.length; i++) {
    for (let j = 0; j < unsafeInputs.length; j++) {
      if (i !== j && unsafeInputs[i].value === unsafeInputs[j].value) {
        console.log("values are same")
        unsafeInputs[j].value = ""
      }
    }
  }
}

unsafeInputs.forEach(input => input.onchange = checkInputs);
<input id="a">
<input id="b">
<input id="c">
slider
  • 12,810
  • 1
  • 26
  • 42
0

You can only do this in one loop, if you sort the array first. Then you can check if two consecutive elements are the same. Otherwise you need two loops, to compare every element with all others (some optimizations are possible to not have O(n²) complexity)

MofX
  • 1,569
  • 12
  • 22