const findTheNumber = (array: number[]) => {
const dict = new Map()
return array.find((item) => {
if (dict.has(item)) {
return item
} else {
dict.set(item, true)
}
})
}
1. what is the difference between map and object?
- the key of the map can be any type, but the key of the object only can be string or symbol.
- 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
})
Top comments (4)
Set
seems like a better choice to solve this: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.
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.
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.