JavaScript Arrays & Strings - Methods & Exercises
1. Array Methods
1.1 Adding/Removing Elements
- push() -> adds to end
- pop() -> removes from end
- shift() -> removes from start
- unshift() -> adds to start
Example:
let arr = [1, 2, 3];
arr.push(4); // [1,2,3,4]
arr.pop(); // [1,2,3]
arr.shift(); // [2,3]
arr.unshift(0); // [0,2,3]
1.2 Iteration & Transformation
- map() -> transforms each element
- filter() -> filters based on condition
- reduce() -> reduces array to single value
Example:
let nums = [1,2,3,4];
let doubled = nums.map(n => n*2); // [2,4,6,8]
let evens = nums.filter(n => n%2===0); // [2,4]
let sum = nums.reduce((acc, n) => acc+n, 0); // 10
1.3 Searching & Checking
- includes() -> checks for element
- indexOf() -> finds index
- find() -> finds first matching element
- some() -> checks if any element passes test
- every() -> checks if all elements pass test
Example:
nums.includes(3); // true
nums.indexOf(2); // 1
nums.find(n => n>2); // 3
nums.some(n => n>3); // true
nums.every(n => n>0); // true
1.4 Other Useful Methods
- slice() -> returns a part of array
- splice() -> add/remove elements at specific index
- concat() -> combine arrays
- join() -> array to string
Example:
nums.slice(1,3); // [2,3]
nums.splice(2,1,'a'); // replaces 1 element at index 2
[1,2].concat([3,4]); // [1,2,3,4]
nums.join('-'); // "1-2-3-4"
2. String Methods
2.1 Access & Modify
- length -> string length
- charAt(index) -> character at index
- toUpperCase(), toLowerCase() -> change case
- trim() -> removes whitespace
Example:
let str = " Hello ";
str.length; // 7
str.charAt(1); // "H"
str.toUpperCase(); // " HELLO "
str.trim(); // "Hello"
2.2 Searching
- includes() -> checks substring
- indexOf() -> position of substring
- startsWith() / endsWith() -> checks start/end
Example:
str.includes("He"); // true
str.indexOf("l"); // 2
str.startsWith(" H"); // true
str.endsWith(" "); // true
2.3 Extracting
- slice(start, end) -> extracts substring
- substring(start, end) -> similar to slice
- substr(start, length) -> extract by length
Example:
str.slice(1,5); // "Hell"
str.substring(1,5); // "Hell"
str.substr(1,3); // "Hel"
2.4 Replacing & Splitting
- replace(old, new) -> replace substring
- split(separator) -> split string to array
Example:
str.replace("Hello", "Hi"); // " Hi "
str.trim().split(" "); // ["Hello"]
2.5 Others
- repeat(n) -> repeat string
- padStart(n, char) / padEnd(n, char) -> padding
Example:
"Hi".repeat(3); // "HiHiHi"
"5".padStart(3,"0"); // "005"
3. Exercises
1. Given [1,2,3,4,5], use map to get squares.
2. Filter out odd numbers from [1,2,3,4,5].
3. Reduce [1,2,3,4] to sum.
4. Check if string "Hello World" includes "World".
5. Convert " javascript " to uppercase and trim spaces.
6. Split "apple,banana,orange" into array.
7. Join [1,2,3] into "1-2-3".