DEV Community

KazooTTT
KazooTTT

Posted on

how to find the repeated number of an array?

const findTheNumber = (array: number[]) => {
  const dict = new Map()
  return array.find((item) => {
    if (dict.has(item)) {
      return item
    } else {
      dict.set(item, true)
    }
  })
}
Enter fullscreen mode Exit fullscreen mode

1. what is the difference between map and object?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#objects_vs._maps

  1. the key of the map can be any type, but the key of the object only can be string or symbol.
  2. the map has order.

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

2. how to get the target item from a array?

use the find api of the Array

Array.prototype.find()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

how to use:

// find the first item that can be divided by 2(evenοΌ‰
const array = [1,2,3,4]
const target = array.find(item=>{
  return item/2===0
})
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Set seems like a better choice to solve this:

const findTheNumber = (arr, s=new Set()) => arr.find(x=>(s.size==s.add(x).size)&&x)

console.log(findTheNumber([1, 2, 3, 4, 2, 5])) // 2
Enter fullscreen mode Exit fullscreen mode
Collapse
 
moopet profile image
Ben Sinclair

I don't know about that... the original is a little difficult to follow (it's not obvious what findTheNumber should do) but it's clear if you spend a few seconds reading the function.

What you've done seems to be less readable to me, partly because of the construct but also because of the lack of whitespace and use of one-character variable names.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

I wrote it as a one-liner as that's how it naturally comes out of my brain for some reason, but it could be re-written to suit tastes of readability if needs be.

Collapse
 
kazoottt profile image
KazooTTT

Thank you for your reply! It is very helpful to me.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.