Amos Machora
Amos Machora

Reputation: 545

Best way to filter an array of objects by Index in JavaScript

I have an array of objects like this

export const productArray = [

  { 
    imgUrl: images.beautifulinwhite,
    productName: "White Flowers",
    oldPrice: "$45.99",
    newPrice: "$35.99",
  },
  {
    imgUrl: images.blueandpinkjeans,
    productName: "Blue and Pink Jeans",
    oldPrice: "$57.99",
    newPrice: "$40.99",
  },
  {
    imgUrl: images.girlinyellow,
    productName: "Yellow Tshirt",
    oldPrice: "$53.99",
    newPrice: "$37.99",
  },
  {
    imgUrl: images.ladyinblack,
    productName: "Black Hoodie",
    oldPrice: "$40.99",
    newPrice: "$33.99",
  },
]

How do I filter this array to only get the first two objects? I don't want to filter them by their attributes. I want to filter using their indexes .

Upvotes: 0

Views: 1346

Answers (1)

Sanches
Sanches

Reputation: 36

The best way to filter the array by index is using the slice() method:

const productArrayFiltered = productArray.slice(0, 2);

From MDN:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

Side note: it's important to remember that the method returns a new array that must be assigned to a new constant or variable.

Upvotes: 2

Related Questions