🚀 JavaScript Arrays & String Methods Complete Guide

📋 Array Methods

🔄 Mutating Methods (Change Original Array)

push() - Add elements to end

let fruits = ['apple', 'banana']; fruits.push('orange', 'grape'); console.log(fruits); // ['apple', 'banana', 'orange', 'grape'] console.log(fruits.length); // Returns new length: 4

pop() - Remove last element

let numbers = [1, 2, 3, 4, 5]; let removed = numbers.pop(); console.log(numbers); // [1, 2, 3, 4] console.log(removed); // 5

unshift() - Add elements to beginning

let colors = ['red', 'blue']; colors.unshift('green', 'yellow'); console.log(colors); // ['green', 'yellow', 'red', 'blue']

shift() - Remove first element

let animals = ['cat', 'dog', 'bird']; let first = animals.shift(); console.log(animals); // ['dog', 'bird'] console.log(first); // 'cat'

splice() - Add/remove elements at any position

let items = ['a', 'b', 'c', 'd', 'e']; // Remove 2 elements starting at index 1, add 'x', 'y' let removed = items.splice(1, 2, 'x', 'y', 'z'); console.log(items); // ['a', 'x', 'y', 'z', 'd', 'e'] console.log(removed); // ['b', 'c']

sort() - Sort elements

let words = ['banana', 'apple', 'cherry']; words.sort(); console.log(words); // ['apple', 'banana', 'cherry'] let nums = [10, 2, 30, 4]; nums.sort((a, b) => a - b); console.log(nums); // [2, 4, 10, 30]

reverse() - Reverse array

let letters = ['a', 'b', 'c', 'd']; letters.reverse(); console.log(letters); // ['d', 'c', 'b', 'a']

🔍 Non-Mutating Methods (Return New Array/Value)

concat() - Join arrays

let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let combined = arr1.concat(arr2, [7, 8]); console.log(combined); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(arr1); // [1, 2, 3] (unchanged)

slice() - Extract portion of array

let original = ['a', 'b', 'c', 'd', 'e']; let portion = original.slice(1, 4); console.log(portion); // ['b', 'c', 'd'] console.log(original.slice(-2)); // ['d', 'e']

join() - Convert array to string

let elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // 'Fire,Air,Water' console.log(elements.join(' - ')); // 'Fire - Air - Water' console.log(elements.join('')); // 'FireAirWater'

indexOf() / lastIndexOf() - Find element index

let data = ['apple', 'banana', 'apple', 'cherry']; console.log(data.indexOf('apple')); // 0 console.log(data.lastIndexOf('apple')); // 2 console.log(data.indexOf('grape')); // -1 (not found)

includes() - Check if element exists

let fruits = ['apple', 'banana', 'cherry']; console.log(fruits.includes('banana')); // true console.log(fruits.includes('grape')); // false

🔄 Iteration Methods

forEach() - Execute function for each element

let numbers = [1, 2, 3, 4]; numbers.forEach((num, index) => { console.log(`Index ${index}: ${num * 2}`); }); // Index 0: 2, Index 1: 4, Index 2: 6, Index 3: 8

map() - Transform each element

let numbers = [1, 2, 3, 4]; let doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] console.log(numbers); // [1, 2, 3, 4] (unchanged)

filter() - Filter elements by condition

let numbers = [1, 2, 3, 4, 5, 6]; let evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // [2, 4, 6] let people = [{name: 'John', age: 25}, {name: 'Jane', age: 17}]; let adults = people.filter(person => person.age >= 18); console.log(adults); // [{name: 'John', age: 25}]

reduce() - Reduce to single value

let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 15 let words = ['Hello', 'World', 'JavaScript']; let sentence = words.reduce((acc, word) => acc + ' ' + word); console.log(sentence); // 'Hello World JavaScript'

find() / findIndex() - Find first matching element

let users = [ {id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 3, name: 'Bob'} ];
let user = users.find(u => u.id === 2); console.log(user); // {id: 2, name: 'Jane'}
let index = users.findIndex(u => u.name === 'Bob'); console.log(index); // 2

some() / every() - Test elements

let numbers = [2, 4, 6, 8];
console.log(numbers.some(num => num > 5)); // true console.log(numbers.every(num => num % 2 === 0)); // true let mixed = [2, 3, 4, 6]; console.log(mixed.every(num => num % 2 === 0)); // false

📝 String Methods

🔍 Search and Access Methods

charAt() / charCodeAt() - Get character at index

let text = "Hello World";
console.log(text.charAt(0)); // 'H' console.log(text.charAt(6)); // 'W' console.log(text.charCodeAt(0)); // 72 (ASCII code for 'H') console.log(text[4]); // 'o' (bracket notation)

indexOf() / lastIndexOf() - Find substring position

let sentence = "The quick brown fox jumps over the lazy dog";
console.log(sentence.indexOf("quick")); // 4 console.log(sentence.indexOf("the")); // 31 (case sensitive) console.log(sentence.lastIndexOf("the")); // 31 console.log(sentence.indexOf("cat")); // -1 (not found)

search() - Search with regex

let text = "The price is $25.99";
console.log(text.search(/\d+/)); // 13 (position of first digit) console.log(text.search(/cat/)); // -1 (not found)

includes() / startsWith() / endsWith() - Check substring

let email = "user@example.com";
console.log(email.includes("@")); // true console.log(email.startsWith("user")); // true console.log(email.endsWith(".com")); // true console.log(email.includes("gmail")); // false

✂️ Extraction Methods

substring() - Extract substring

let text = "JavaScript Programming";
console.log(text.substring(0, 10)); // 'JavaScript' console.log(text.substring(11)); // 'Programming' console.log(text.substring(4, 10)); // 'Script'

substr() - Extract substring with length

let text = "Hello World";
console.log(text.substr(0, 5)); // 'Hello' console.log(text.substr(6, 5)); // 'World' console.log(text.substr(6)); // 'World'

slice() - Extract portion (supports negative indices)

let text = "Hello World";
console.log(text.slice(0, 5)); // 'Hello' console.log(text.slice(6)); // 'World' console.log(text.slice(-5)); // 'World' console.log(text.slice(-5, -1)); // 'Worl'

🔄 Transformation Methods

toLowerCase() / toUpperCase() - Change case

let text = "Hello World";
console.log(text.toLowerCase()); // 'hello world' console.log(text.toUpperCase()); // 'HELLO WORLD' console.log(text); // 'Hello World' (unchanged)

trim() / trimStart() / trimEnd() - Remove whitespace

let text = " Hello World ";
console.log(text.trim()); // 'Hello World' console.log(text.trimStart()); // 'Hello World ' console.log(text.trimEnd()); // ' Hello World'

replace() / replaceAll() - Replace text

let text = "Hello World, Hello Universe";
console.log(text.replace("Hello", "Hi")); // 'Hi World, Hello Universe' console.log(text.replaceAll("Hello", "Hi")); // 'Hi World, Hi Universe' console.log(text.replace(/Hello/g, "Hi")); // 'Hi World, Hi Universe' (regex)

split() - Split into array

let csv = "apple,banana,cherry,date";
console.log(csv.split(",")); // ['apple', 'banana', 'cherry', 'date'] let sentence = "Hello World JavaScript";
console.log(sentence.split(" ")); // ['Hello', 'World', 'JavaScript'] console.log(sentence.split("")); // ['H','e','l','l','o',' ','W','o','r','l','d',' ','J','a','v','a','S','c','r','i','p','t']

repeat() - Repeat string

let text = "Hello ";
console.log(text.repeat(3)); // 'Hello Hello Hello ' console.log("*".repeat(10)); // '**********'

padStart() / padEnd() - Pad string

let num = "5";
console.log(num.padStart(3, "0")); // '005' console.log(num.padEnd(3, "0")); // '500' let text = "Hello";
console.log(text.padStart(10, "*")); // '*****Hello' console.log(text.padEnd(10, "*")); // 'Hello*****'

🔤 Other Useful Methods

match() - Match with regex

let text = "The price is $25.99 and $15.50";
console.log(text.match(/\$\d+\.\d+/)); // ['$25.99'] console.log(text.match(/\$\d+\.\d+/g)); // ['$25.99', '$15.50']

concat() - Concatenate strings

let first = "Hello"; let second = "World";
console.log(first.concat(" ", second)); // 'Hello World' console.log(first.concat(" ", second, "!")); // 'Hello World!'

localeCompare() - Compare strings

let a = "apple"; let b = "banana";
console.log(a.localeCompare(b)); // -1 (a comes before b) console.log(b.localeCompare(a)); // 1 (b comes after a) console.log(a.localeCompare("apple")); // 0 (equal)

🔗 Array and String Method Combinations

🎯 Common Real-World Combinations

1. Process CSV Data

let csvData = "John,25,Engineer\nJane,30,Designer\nBob,35,Manager";
let users = csvData.split('\n') .map(line => line.split(',')) .map(([name, age, job]) => ({ name: name.trim(), age: parseInt(age), job: job.trim() })) .filter(user => user.age >= 30);
console.log(users); // [{name: 'Jane', age: 30, job: 'Designer'}, {name: 'Bob', age: 35, job: 'Manager'}]

2. Clean and Process Text Data

let messyText = " HELLO world , JAVASCRIPT programming , DATA processing ";
let cleanWords = messyText.trim() .toLowerCase() .split(',') .map(word => word.trim()) .filter(word => word.length > 0) .map(phrase => phrase.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1) ).join(' '));
console.log(cleanWords); // ['Hello World', 'Javascript Programming', 'Data Processing']

3. Email Validation and Processing

let emailList = "john@gmail.com, JANE@YAHOO.COM, bob@invalid, alice@hotmail.com ";
let validEmails = emailList.split(',') .map(email => email.trim().toLowerCase()) .filter(email => email.includes('@') && email.includes('.')) .filter(email => email.indexOf('@') > 0 && email.lastIndexOf('.') > email.indexOf('@')) .sort();
console.log(validEmails); // ['alice@hotmail.com', 'jane@yahoo.com', 'john@gmail.com']

4. Word Frequency Counter

let text = "The quick brown fox jumps over the lazy dog. The dog was really lazy.";
let wordFreq = text.toLowerCase() .replace(/[^\w\s]/g, '') .split(' ') .filter(word => word.length > 0) .reduce((freq, word) => { freq[word] = (freq[word] || 0) + 1; return freq; }, {});
console.log(wordFreq); // {the: 2, quick: 1, brown: 1, fox: 1, jumps: 1, over: 1, lazy: 2, dog: 2, was: 1, really: 1}

5. URL Path Processing

let urls = [ "https://example.com/users/123/profile", "https://example.com/products/456/details", "https://example.com/orders/789/summary" ];
let processedUrls = urls.map(url => { let pathParts = url.split('/').slice(3); // Remove protocol and domain return { originalUrl: url, resource: pathParts[0], id: pathParts[1], action: pathParts[2], breadcrumb: pathParts.join(' > ') }; });
console.log(processedUrls); // [{originalUrl: '...', resource: 'users', id: '123', action: 'profile', breadcrumb: 'users > 123 > profile'}, ...]

6. Data Transformation Pipeline

let rawData = "Product1:$25.99:Electronics,Product2:$15.50:Books,Product3:$99.99:Electronics";
let products = rawData.split(',') .map(item => { let [name, price, category] = item.split(':'); return { name: name.trim(), price: parseFloat(price.replace('$', '')), category: category.trim() }; }) .filter(product => product.price > 20) .sort((a, b) => b.price - a.price) .map(product => ({ ...product, displayPrice: `$${product.price.toFixed(2)}`, displayName: product.name.replace(/(\d+)/, ' $1').trim() }));
console.log(products); // Sorted products with formatted names and prices

7. Search and Highlight

let articles = [ "JavaScript is a powerful programming language", "Python is great for data science", "JavaScript frameworks are very popular" ];
let searchTerm = "javascript";
let results = articles .map((article, index) => ({ text: article, index })) .filter(item => item.text.toLowerCase().includes(searchTerm.toLowerCase())) .map(item => ({ ...item, highlighted: item.text.replace( new RegExp(searchTerm, 'gi'), match => `${match}` ), snippet: item.text.length > 50 ? item.text.substring(0, 50) + '...' : item.text }));
console.log(results); // Articles containing "javascript" with highlighting

8. Form Data Validation

let formData = [ "name: John Doe", "email: john@example.com", "phone: 123-456-7890", "age: 25" ];
let validatedData = formData .map(field => field.split(':').map(part => part.trim())) .reduce((acc, [key, value]) => { acc[key] = value; return acc; }, {})
// Validation rules
let validationResults = Object.entries(validatedData) .map(([key, value]) => { let isValid = true; let errors = []; switch(key) { case 'email': isValid = value.includes('@') && value.includes('.'); if (!isValid) errors.push('Invalid email format'); break; case 'phone': isValid = value.replace(/\D/g, '').length === 10; if (!isValid) errors.push('Phone must be 10 digits'); break; case 'age': isValid = !isNaN(value) && parseInt(value) >= 18; if (!isValid) errors.push('Age must be 18 or older'); break; } return { field: key, value, isValid, errors }; });
console.log(validationResults); // Validation results for each field

🎮 Interactive Demo

Try out different array and string methods!