Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active September 1, 2023 09:04
Show Gist options
  • Save ariesmcrae/2f407fa76a7efcfb486bbc783155bf02 to your computer and use it in GitHub Desktop.
Save ariesmcrae/2f407fa76a7efcfb486bbc783155bf02 to your computer and use it in GitHub Desktop.
Typescript: Find an item from one list to another

Typescript: Find an item from one list to another

Version 1: the imperative approach

type Item = {
  id: string
  name: string
}

const items1: Item[] = [
  {
    id: 'id123',
    name: 'name123'
  },
  {
    id: 'id789',
    name: 'name789'
  }
]

const items2: Item[] = [
  {
    id: 'id456',
    name: 'name456'
  },
  {
    id: 'id123',
    name: 'name123'
  }
]

const extrastList: Item[] = []

const main = async (): Promise<void> => {
  items1.forEach((item1: Item) => {
    // find items1.id in items2
    const itemFound: Item | undefined = items2.find((item2) => item1.id === item2.id)

    if (itemFound) {
      extrastList.push(item1)
    }
  })

  console.log(extrastList)
}

void (async () => {
  await main()
})()

Version 2: The declarative approach

const main = async (): Promise<void> => {
  const extrastList: Item[] = items1.filter((item1) =>
    items2.some((item2) => item1.id === item2.id)
  );

  console.log(extrastList);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment