Tanveer Singh
Tanveer Singh

Reputation: 51

Math.Abs() in Javascript - array unexpected

If i pass array in Math.abs() I cannot understand why it returns -3, why my value is changing from positive to negative

let test1 = [2, 3, 3, 1, 5, 2]
let test2 = [2, 4, 3, 5, 1]
function firstDuplicate(a) {
  for (let i of a) {
    console.log(i);
    let posi = Math.abs(i) - 1;
    //console.log(posi);
  }

}
console.log(firstDuplicate(test1))
console.log(firstDuplicate(test2))

and I don't understand how Math.abs is working, real code is below

function firstDuplicate(a) {
  for (let i of a) {
    let posi = Math.abs(i) - 1
    if (a[posi] < 0) return posi + 1
    a[posi] = a[posi] * -1
  }

  return -1
}

Upvotes: 0

Views: 1379

Answers (2)

Fabian
Fabian

Reputation: 480

Your code has some flaws.

  for (let i of a) { 
    let posi = Math.abs(i) - 1
    if (a[posi] < 0) return posi + 1
    a[posi] = a[posi] * -1
  }

Lets step through this, step by step with an example:

  1. (let i of a) will give you each value in the arrray. e.g. on first loop i=2
  2. let posi = Math.abs(i) - 1 will convert the number from the array to an absolute integer and substract 1. Now posi would be (2 - 1) = 1.
  3. a[posi] will now get the value from the array at index 1 which is 3 (in array test1)

  4. if (a[posi] < 0) return posi + 1 this will never return unless there is a negative number or 0 somewhere in your data (Math.abs(0) - 1 === -1).

  5. a[posi] = a[posi] * -1 Now you change the value in your array. In our example: a[1] = a[1] * -1. This will leave the array in the following state: [2, -3, 3, 1, 5, 2]

I hope that this helps you to understand your own code. Maybe google for a solution on "how to find first duplicate in aray" and just copy that.

Upvotes: 1

Luke
Luke

Reputation: 361

Math.abs() returns absolute value of number. But u re multiplying your absolute value by negative 1. thats why you get negative value

a[posi] = a[posi] * -1

Upvotes: 2

Related Questions