0

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 .

3
  • 1
    The first object in the array is: productArray[0] and the second is: productArray[1]. If you need to pull these two out into another array: [productArray[0], productArray[1]]. If you definitely need to use .filter using the index: productArray.filter((x, idx) => idx < 2); Commented Mar 12, 2022 at 14:50
  • If you just want first 2, why do any computations? just do productArray[0].smthng and productArray[1].smthng Commented Mar 12, 2022 at 14:50
  • 1
    To get the first few elements you can just use array.slice(0, n), where n is the number of elements you want to get Commented Mar 12, 2022 at 14:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What does the term shallow copy mean
Shallow copy is basically a term for a type of copying the data (in this case an array) in a superficial way, we also have the deep copy that will make a true copy of the data. You can read about it here...
In fact, shallow copy means that if you define a new value to productArray indexed of X, the value will also change in the productArrayFiltered. So if you do productArray[0] = 20, and console.log(productArrayFiltered[0]), the printed value will be 20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.