Crud operation : filter, delete, and update element in Array

Crud operation : filter, delete, and update element in Array 

The code you provided seems to define an array of products and a few operations to filter, delete, and update them. However, there are a couple of things to address:

  1. updateproducts function:

    • The updateproducts function currently has a small issue. You are trying to return false for the products that do not match the specified name, which can result in an array of false values for the non-matching items. Instead, you should return the non-matching items unchanged. Otherwise, you would be removing them from the result. You should return the original product when it doesn't match the name.
  2. deleteproducts function:

    • splice mutates the original array, removing elements in place, so this will change the products array directly. This can lead to unexpected behavior if you're trying to maintain the original array in subsequent operations. If you want to avoid modifying the original array, you could create a copy of it first.
  3. Your code is almost correct, but there are a couple of issues, especially with the usage of reduce and how you're calculating the total price. Let's go over each section:

    1. map implementation:

    You're trying to use map to accumulate the total price in totalprice, but this approach is not quite ideal because map is designed to return a new array, not for side effects like accumulation. You can still use map if you'd like, but it's not the most appropriate method here.

    2. reduce implementation:

    In the reduce function, you're trying to add accum.price and curElem.price. The issue is that accum is an accumulator, which starts as a number (0 in this case). So, accum.price will cause an error since accum is not an object.

    Here's the corrected version of your code:

    Explanation:
    1. map method:

      • You are using map to accumulate the total price, but it's better to use reduce for accumulation because map is meant to transform an array into a new array.
      • The result r[r.length - 1] is correct to get the final accumulated price, but this is not a standard use case for map.
    2. reduce method:

      • The reduce function is ideal for accumulation. It takes two arguments:
        • accum: The accumulator (starts with 0).
        • curElem: The current element being processed.
      • The expression accum + curElem.price sums the prices of all products. You don't need to access accum.price, because accum is just a number here.


Here is a code with these improvements:


let products = [
    { name: "laptop", price: 1200 },
    { name: "phone", price: 800 },
    { name: "tablet", price: 300 },
    { name: "smartwatch", price: 150 },
]

console.log(products);


const filterproducts = (data) => {
    return data.filter(item => { return item.price <= 500 });
}

const deleteproducts = (data) => {
    return data.splice(0, 2);
}

const updateproducts = (name) => {
    return products.map((item) => {
        if (item.name == name) {
            return { name: "smart", price: 100, status: true };
        } else {
            return false;
        }
    })
}

// console.log(filterproducts(products));
// deleteproducts(products);
console.log(updateproducts("laptop"));
console.log(products);

// Using map (not recommended for accumulating totals, but works)
let totalprice = 0;
let r = products.map((item, id) => {
    totalprice += item.price;
    return totalprice;
});
console.log(r[r.length - 1]); // The last value in the array is the total price

// Correct way using reduce to calculate total price of products
const total = products.reduce((accum, curElem) => {
  return accum + curElem.price; // Just sum the prices
}, 0);

console.log(total); // Output total price using reduce



Changes:
  1. In updateproducts, if a product name matches, it is updated, but the non-matching items are kept unchanged.
  2. In deleteproducts, I replaced splice with slice, which creates a new array without mutating the original array. You could use splice if mutation is acceptable, but it directly changes the products array.
  3. The console.log statements show the changes or original array states.

Now, you can run the code and see how it behaves. Here's a quick summary:

  • The filterproducts function will return items with a price less than or equal to 500.
  • The deleteproducts function will delete the first two products and return a new array.
  • The updateproducts function will update the product matching the given name and leave the others unchanged.

Comments

Popular posts from this blog

Lets build a Markdown blog using Next.js, Shadcn, Tailwind, Pieces, Remark & Rehype 🔥

React Portflio Website Basic to Advance

Todo List app using html,js and tailwind.css with features login,logout,storing the data in localstorage addtodos,deletetodos and updating todos,toastify library and many more