Advertisement
xerocool-101

009 splice method

Apr 20th, 2025 (edited)
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.03 KB | Software | 0 0
  1. // Remove elements only
  2. const fruits = ["apple", "banana", "cherry", "date"];
  3. fruits.splice(1, 2); // start at index 1, delete 2 items
  4.  
  5. console.log(fruits); // ["apple", "date"]
  6.  
  7. // Add elements only
  8. const colors = ["red", "green", "blue"];
  9. colors.splice(1, 0, "yellow");
  10.  
  11. console.log(colors); // ["red", "yellow", "green", "blue"]
  12.  
  13. // Replace elements
  14. const nums = [10, 20, 30];
  15. nums.splice(1, 1, 25); // replace 20 with 25
  16.  
  17. console.log(nums); // [10, 25, 30]
  18.  
  19. // Capture removed elements
  20. const pets = ["dog", "cat", "rabbit"];
  21. const removed = pets.splice(1, 1);
  22.  
  23. console.log(pets);    // ["dog", "rabbit"]
  24. console.log(removed); // ["cat"]
  25.  
  26. // 🎯 Real-World Use Cases
  27. // ✅ Remove an item from a cart by index
  28. const cart = ["Shirt", "Shoes", "Hat"];
  29. const index = 1;
  30. cart.splice(index, 1); // Removes "Shoes"
  31.  
  32. console.log(cart); // ["Shirt", "Hat"]
  33.  
  34. // ✅ Replace user role in admin panel
  35. const roles = ["User", "Editor", "Guest"];
  36. roles.splice(2, 1, "Admin");
  37.  
  38. console.log(roles); // ["User", "Editor", "Admin"]
  39.  
  40.  
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement