Isabella Chen - 1 year ago 59

Javascript Question

Given an array of numbers, I wish to use javascript's .some() method to find the first pair of mirror image numbers and return the pair.

e.g. [454,86,57,75,16,88]) should return [57,75]. If there are no numbers that mirror each other, I want to return [-1,-1]. I managed to get up to the point where if there are mirror image numbers, the numbers are returned. However, I can't get it to return [-1,-1]. Where did I go wrong?

`var a=0`

var b=0

arr=[13,15,19,32,49,61,73]

arr.some((x,i)=>{

a=arr[i]

b=arr[i+1]

b= switchIt(b)

if(a!==b){ //what if there are no mirror image numbers found?

a = -1

b = -1

}else{

return a==b

}

})

function switchIt(n){

n= n.toString()

n= n.split("")

var [x,y,z]=[n[0],n[1],n[2]]

n= [z,y,x]

n= n.join("")

n= parseInt(n)

return n

}

console.log([a,switchIt(b)])

Answer Source

One simple ajust and your code will work as expected:

```
arr.some((x,i)=>{
var end = i >= (arr.length - 1);
a=arr[i]
if (!end) {
b=arr[i+1]
b = switchIt(b)
}
if(a!==b || end){ //note the OR with end variable here
a = -1
b = -1
}else{
return a==b
}
})
```

The ajust consists in test when some function find the end of array