get item in array by id in javascript

To get an item in an array by its ID in JavaScript, you can use:

  1. The find() method: The find() method returns the value of the first element in an array that satisfies a provided condition. You can use find() to search for an item with a specific ID property.
index.tsx
const idToFind = 2;
const itemsArray = [
  { id: 1, name: "Item 1" },
  { id: 2, name: "Item 2" },
  { id: 3, name: "Item 3" }
];

const foundItem = itemsArray.find(item => item.id === idToFind);

console.log(foundItem); // { id: 2, name: "Item 2" }
250 chars
11 lines
  1. The filter() method: The filter() method creates a new array with all elements that pass the test implemented by the provided function. You can use filter() to search for all items with a specific ID property.
index.tsx
const idToFind = 2;
const itemsArray = [
  { id: 1, name: "Item 1" },
  { id: 2, name: "Item 2" },
  { id: 3, name: "Item 3" },
  { id: 2, name: "Item 2 - Duplicate ID" }
];

const foundItems = itemsArray.filter(item => item.id === idToFind);

console.log(foundItems); // [{ id: 2, name: "Item 2" }, { id: 2, name: "Item 2 - Duplicate ID" }]
342 chars
12 lines

Note that find() returns only the first match it finds, whereas filter() can return multiple matches.

related categories

gistlibby LogSnag