简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM