0

I have below const

const cartProducts = props.cartSlice;

whose output is below array

Array [
  Object {
    "cartQuantity": 3,
    "product": "5f15d92ee520d44421ed8e9b",
  },
  Object {
    "cartQuantity": 2,
    "product": "5f15d964e520d44421ed8e9c",
  },
  Object {
    "cartQuantity": 1,
    "product": "62e5285f92b4fde9dc8a384c",
  },
  Object {
    "cartQuantity": 4,
    "product": "5f15d9b3e520d44421ed8e9d",
  },
]

I am trying to write some code in reactjs to output separate arrays with the only the cartQuantity as below

Array [
  3,
]
Array[
  2,
]
Array[
  1,
]
Array[
  4,
]

The closest I have come to achieving this is below which is consolidating all the cartQuantity in a single array.

const quantity = cartProducts.map((item, i) => item.cartQuantity);

Array [
  3,
  2,
  1,
  4,
]

How can I modify my query to output separate arrays for each cartQuantity?

1
  • Return => [item.cartQuantity] Commented Oct 4, 2022 at 13:17

1 Answer 1

1

You already mapped the initial array into an array of quantities, now if you want to get an array of arrays, with one quantity into each inner array, then it suffices to make the map callback return an Array with such quantity.

const quantity = cartProducts.map((item, i) => [item.cartQuantity]);

Array [
  Array [
    3
  ],
  Array[
    2
  ],
  Array[
    1
  ],
  Array[
    4
  ]
]
Sign up to request clarification or add additional context in comments.

1 Comment

It had not crossed my mind.. It is working and the console.log display an array of arrays. I thought it would address the problem I faced here.. stackoverflow.com/questions/73882335/…

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.