JavaScript Array Practice Questions
Focus methods: push, pop, shift, unshift, slice, splice, indexOf, lastIndexOf, includes
1. Add & Remove (push, pop)
let arr = [10, 20, 30];
• Add 40 and 50 to the end
• Remove last element
• Print final array
2. Shift & Unshift
let arr = ["b", "c", "d"];
• Add "a" at beginning
• Remove first element
• Print result
3. Check Element Exists (includes)
let arr = ["apple", "banana", "mango"];
• Check if "banana" exists → print "Found" or "Not Found"
• Check if "grapes" exists
4. First & Last Occurrence
let arr = [1, 2, 3, 2, 4, 2];
• Find first occurrence of 2
• Find last occurrence of 2
5. Second Occurrence (indexOf)
• Find 2nd occurrence index of 2
6. Extract Subarray (slice)
let arr = [10, 20, 30, 40, 50];
• Extract [20, 30, 40]
• Print original array also (should not change)
7. Remove Middle Element (splice)
let arr = [10, 20, 30, 40, 50];
• Remove 30 using splice
• Print updated array
8. Replace Element (splice)
let arr = ["HTML", "CSS", "JS"];
• Replace "CSS" with "Bootstrap"
9. Insert Without Removing (splice)
let arr = [1, 2, 5];
• Insert 3 and 4 between 2 and 5
10. Remove Multiple Elements (splice)
let arr = [1, 2, 3, 4, 5, 6];
• Remove 3, 4, 5 using single splice
11. Slice vs Splice
let arr = [1, 2, 3, 4];
• Use slice to get [2, 3]
• Use splice to remove [2, 3]
• Print both results and original array
12. Remove First & Last Together
let arr = [100, 200, 300, 400];
• Remove first element
• Remove last element
• Print final array
13. Check Duplicate Using indexOf
let arr = [1, 2, 3, 2, 4];
• Check if any element appears more than once
• Hint: Compare indexOf() and lastIndexOf()
14. Remove Specific Element
let arr = [10, 20, 30, 20, 40];
• Remove first occurrence of 20
15. Remove All Occurrences
let arr = [10, 20, 30, 20, 40, 20];
• Remove all 20 using loop + splice
16. Insert at Specific Position
let arr = [1, 2, 4, 5];
• Insert 3 at index 2
17. Find or Add Element
let arr = [10, 20, 30];
• If 40 exists → print index
• If not → add it to array
18. Extract Last 3 Elements
let arr = [1, 2, 3, 4, 5, 6];
• Use slice to get last 3 elements
19. Remove Element Using Index
let arr = ["a", "b", "c", "d"];
• Remove element at index 2
20. Combine Methods
let arr = [10, 20, 30, 40];
• Add 5 at beginning
• Add 50 at end
• Remove first element
• Remove last element
• Extract middle elements