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

Time:03-13

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 .

CodePudding user response:

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.

  • Related