Array might not be the right data structure for you

Draft Disclaimer: Please note that this article is currently in draft form and may undergo revisions before final publication. The content, including information, opinions, and recommendations, is subject to change and may not represent the final version. We appreciate your understanding and patience as we work to refine and improve the quality of this article. Your feedback is valuable in shaping the final release.

Language Mismatch Disclaimer: Please be aware that the language of this article may not match the language settings of your browser or device.
Do you want to read articles in English instead ?

Array might not be the right data structure for you Map as a better data structure than array

  • Web development open to almost everyone able to do a bit of logical thinking
  • no need to come from a technical background
  • few things I am seeing people miss that might be obvious to other with technical background (ie Bachelor or Masters in Science)
  • poor choice in data structure
  • example with add to cart
  • This example is in react/react native but concept apply to most tech
addCartItem: (state, action) => {
 state.items.push({product, quantity})
}
  • Then we want to increment quantity when same product added
  • the first thought or obvious solution
 addCartItem: (state, action) => {
 const newProduct = action.payload.product
const productIndex = state.items.findIndex(item => item.product.id == newProduct.id)
if (productIndex != -1) {
 state.items[productIndex].quantity++
} else {
 state.items.push({product: newProduct, quantity: 1})
}

  • let’s say now you want to change quantity (plus or minus)
changeQuantity: (state, action) {
 const {productId, amount} = action.payload
 const index = state.items.findIndex(item => item.product.id == productId)
 if (index != -1) {
 state.items[index].quantity += amount
 if (state.items[index].quantity # # <= 0) {
 state.items.splice(index, 1)
 }
 }

}