Skip to content

Instantly share code, notes, and snippets.

@rimzzlabs
Created November 23, 2022 03:14
Show Gist options
  • Save rimzzlabs/700d3525731bda0cb6646e9a2b27eafe to your computer and use it in GitHub Desktop.
Save rimzzlabs/700d3525731bda0cb6646e9a2b27eafe to your computer and use it in GitHub Desktop.
type Value = Record<string, unknown>
export const arrayObjSearch = <T extends Value>(arr: Array<T>, key: keyof Array<T>[0], target: string): T | null => {
if (!key) throw new TypeError('You should provide what key to find')
if (arr.length === 0) return null
let i = 0
do {
const source = arr[i][key]
if (source === target) return arr[i]
i++
} while (i < arr.length)
return null
}
export const arrayObjIndexSearch = <T extends Value>(
arr: Array<T>,
key: keyof Array<T>[0],
target: string
): number | null => {
if (!key) throw new TypeError('You should provide what key to find')
if (arr.length === 0) return null
let i = 0
do {
const source = arr[i][key]
if (source === target) return i
i++
} while (i < arr.length)
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment