javascript

examples

examples.js
/**
 * ========================================
 * 12.1 Array Fundamentals - Examples
 * ========================================
 *
 * Comprehensive examples of JavaScript arrays.
 */

/**
 * EXAMPLE 1: Creating Arrays
 *
 * Multiple ways to create arrays.
 */

// Array literal (most common)
const fruits = ['apple', 'banana', 'cherry'];
console.log('Literal:', fruits);

// Array constructor
const withConstructor = new Array(1, 2, 3);
console.log('Constructor:', withConstructor);

// Empty array with length
const empty = new Array(5); // [empty × 5]
console.log('Empty slots:', empty.length, empty);

// Array.of() - consistent single-argument behavior
const single = Array.of(5); // [5], not 5 empty slots
console.log('Array.of(5):', single);

// Array.from() - from iterables
const fromString = Array.from('hello');
console.log('From string:', fromString); // ['h', 'e', 'l', 'l', 'o']

// Array.from() with mapping function
const range = Array.from({ length: 5 }, (_, index) => index * 2);
console.log('Range:', range); // [0, 2, 4, 6, 8]

// Array.from() from Set
const uniqueArray = Array.from(new Set([1, 2, 2, 3, 3, 3]));
console.log('From Set:', uniqueArray); // [1, 2, 3]

/**
 * EXAMPLE 2: Accessing Elements
 *
 * Different ways to access array elements.
 */

const letters = ['a', 'b', 'c', 'd', 'e'];

// Bracket notation
console.log('First:', letters[0]); // 'a'
console.log('Third:', letters[2]); // 'c'
console.log('Last (old):', letters[letters.length - 1]); // 'e'

// .at() method (ES2022) - supports negative indices
console.log('First (.at):', letters.at(0)); // 'a'
console.log('Last (.at):', letters.at(-1)); // 'e'
console.log('Second last:', letters.at(-2)); // 'd'

// Out of bounds
console.log('Out of bounds:', letters[10]); // undefined
console.log('Negative (old):', letters[-1]); // undefined

/**
 * EXAMPLE 3: Array Properties
 *
 * Working with array length and type checking.
 */

const numbers = [1, 2, 3, 4, 5];

// Length
console.log('Length:', numbers.length); // 5

// Modifying length (truncates or extends)
const arr = [1, 2, 3, 4, 5];
arr.length = 3;
console.log('Truncated:', arr); // [1, 2, 3]

arr.length = 5;
console.log('Extended:', arr); // [1, 2, 3, empty × 2]

// Type checking
console.log('Is array:', Array.isArray(numbers)); // true
console.log('Is array:', Array.isArray('string')); // false
console.log('Is array:', Array.isArray({ 0: 'a' })); // false

/**
 * EXAMPLE 4: Push, Pop, Shift, Unshift
 *
 * Adding and removing elements from ends.
 */

const stack = ['a', 'b', 'c'];

// push - add to end
stack.push('d');
console.log('After push:', stack); // ['a', 'b', 'c', 'd']

stack.push('e', 'f');
console.log('Push multiple:', stack); // ['a', 'b', 'c', 'd', 'e', 'f']

// pop - remove from end
const popped = stack.pop();
console.log('Popped:', popped, stack); // 'f', ['a', 'b', 'c', 'd', 'e']

// unshift - add to beginning
stack.unshift('x');
console.log('After unshift:', stack); // ['x', 'a', 'b', 'c', 'd', 'e']

// shift - remove from beginning
const shifted = stack.shift();
console.log('Shifted:', shifted, stack); // 'x', ['a', 'b', 'c', 'd', 'e']

/**
 * EXAMPLE 5: Splice - The Swiss Army Knife
 *
 * Remove, insert, or replace elements anywhere.
 */

// splice(startIndex, deleteCount, ...itemsToAdd)

// Remove elements
let arr1 = ['a', 'b', 'c', 'd', 'e'];
const removed = arr1.splice(2, 2); // Remove 2 items starting at index 2
console.log('Removed:', removed); // ['c', 'd']
console.log('After remove:', arr1); // ['a', 'b', 'e']

// Insert elements (deleteCount = 0)
let arr2 = ['a', 'b', 'e'];
arr2.splice(2, 0, 'c', 'd'); // Insert at index 2
console.log('After insert:', arr2); // ['a', 'b', 'c', 'd', 'e']

// Replace elements
let arr3 = ['a', 'b', 'x', 'x', 'e'];
arr3.splice(2, 2, 'c', 'd'); // Replace 2 items with 2 new items
console.log('After replace:', arr3); // ['a', 'b', 'c', 'd', 'e']

// Negative index
let arr4 = ['a', 'b', 'c', 'd', 'e'];
arr4.splice(-2, 1); // Remove 1 item, 2 from end
console.log('Negative splice:', arr4); // ['a', 'b', 'c', 'e']

/**
 * EXAMPLE 6: Slice - Non-Mutating Extract
 *
 * Extract portion without modifying original.
 */

const original = ['a', 'b', 'c', 'd', 'e'];

// slice(startIndex, endIndex) - endIndex not included
console.log('slice(1, 3):', original.slice(1, 3)); // ['b', 'c']
console.log('slice(2):', original.slice(2)); // ['c', 'd', 'e']
console.log('slice(-2):', original.slice(-2)); // ['d', 'e']
console.log('slice(-3, -1):', original.slice(-3, -1)); // ['c', 'd']
console.log('slice() copy:', original.slice()); // [...original]

// Original unchanged
console.log('Original:', original); // ['a', 'b', 'c', 'd', 'e']

/**
 * EXAMPLE 7: Sort and Reverse
 *
 * Sorting and reversing arrays.
 */

// Default sort (alphabetical/string)
const nums = [10, 2, 30, 1, 20];
console.log('Default sort:', [...nums].sort()); // [1, 10, 2, 20, 30] ⚠️

// Numeric ascending sort
console.log(
  'Ascending:',
  [...nums].sort((a, b) => a - b)
); // [1, 2, 10, 20, 30]

// Numeric descending sort
console.log(
  'Descending:',
  [...nums].sort((a, b) => b - a)
); // [30, 20, 10, 2, 1]

// String sort (case-insensitive)
const words = ['Banana', 'apple', 'Cherry'];
console.log(
  'Case-insensitive:',
  [...words].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
);

// Sort objects
const users = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Bob', age: 35 },
];
const sortedByAge = [...users].sort((a, b) => a.age - b.age);
console.log(
  'By age:',
  sortedByAge.map((u) => u.name)
); // ['Jane', 'John', 'Bob']

// Reverse
const reversed = [1, 2, 3, 4, 5].reverse();
console.log('Reversed:', reversed); // [5, 4, 3, 2, 1]

/**
 * EXAMPLE 8: Map - Transform Elements
 *
 * Create new array by transforming each element.
 */

const prices = [10, 20, 30, 40, 50];

// Double each price
const doubled = prices.map((price) => price * 2);
console.log('Doubled:', doubled); // [20, 40, 60, 80, 100]

// Format as currency
const formatted = prices.map((price) => `$${price.toFixed(2)}`);
console.log('Formatted:', formatted);

// With index
const indexed = prices.map((price, index) => ({ index, price }));
console.log('Indexed:', indexed);

// Extract property from objects
const products = [
  { name: 'Apple', price: 1.5 },
  { name: 'Banana', price: 0.75 },
  { name: 'Cherry', price: 2.0 },
];
const names = products.map((p) => p.name);
console.log('Names:', names); // ['Apple', 'Banana', 'Cherry']

/**
 * EXAMPLE 9: Filter - Select Elements
 *
 * Create new array with elements that pass test.
 */

const allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter even numbers
const evens = allNumbers.filter((n) => n % 2 === 0);
console.log('Evens:', evens); // [2, 4, 6, 8, 10]

// Filter greater than 5
const large = allNumbers.filter((n) => n > 5);
console.log('Greater than 5:', large); // [6, 7, 8, 9, 10]

// Filter objects
const people = [
  { name: 'John', age: 30, active: true },
  { name: 'Jane', age: 25, active: false },
  { name: 'Bob', age: 35, active: true },
];

const activeUsers = people.filter((p) => p.active);
console.log(
  'Active:',
  activeUsers.map((p) => p.name)
); // ['John', 'Bob']

const adults = people.filter((p) => p.age >= 30);
console.log(
  'Adults:',
  adults.map((p) => p.name)
); // ['John', 'Bob']

// Chain filter and map
const activeNames = people.filter((p) => p.active).map((p) => p.name);
console.log('Active names:', activeNames); // ['John', 'Bob']

/**
 * EXAMPLE 10: Reduce - Aggregate Values
 *
 * Reduce array to single value.
 */

const values = [1, 2, 3, 4, 5];

// Sum
const sum = values.reduce((acc, val) => acc + val, 0);
console.log('Sum:', sum); // 15

// Product
const product = values.reduce((acc, val) => acc * val, 1);
console.log('Product:', product); // 120

// Find max
const max = values.reduce((a, b) => Math.max(a, b));
console.log('Max:', max); // 5

// Count occurrences
const items = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const counts = items.reduce((acc, item) => {
  acc[item] = (acc[item] || 0) + 1;
  return acc;
}, {});
console.log('Counts:', counts); // { apple: 3, banana: 2, cherry: 1 }

// Group by property
const groupedByAge = people.reduce((acc, person) => {
  const key = person.age >= 30 ? 'adult' : 'young';
  (acc[key] = acc[key] || []).push(person);
  return acc;
}, {});
console.log('Grouped:', groupedByAge);

// Flatten array
const nested = [
  [1, 2],
  [3, 4],
  [5, 6],
];
const flattened = nested.reduce((acc, arr) => [...acc, ...arr], []);
console.log('Flattened:', flattened); // [1, 2, 3, 4, 5, 6]

/**
 * EXAMPLE 11: Find and Includes
 *
 * Search for elements.
 */

const inventory = [
  { id: 1, name: 'Apple', inStock: true },
  { id: 2, name: 'Banana', inStock: false },
  { id: 3, name: 'Cherry', inStock: true },
];

// find - returns first matching element
const banana = inventory.find((item) => item.name === 'Banana');
console.log('Found:', banana); // { id: 2, name: 'Banana', inStock: false }

const notFound = inventory.find((item) => item.name === 'Grape');
console.log('Not found:', notFound); // undefined

// findIndex - returns index of first match
const bananaIndex = inventory.findIndex((item) => item.name === 'Banana');
console.log('Index:', bananaIndex); // 1

// findLast - returns last matching element (ES2023)
const lastInStock = inventory.findLast((item) => item.inStock);
console.log('Last in stock:', lastInStock); // { id: 3, name: 'Cherry' }

// includes - check if element exists
const simpleArray = [1, 2, 3, 4, 5];
console.log('Includes 3:', simpleArray.includes(3)); // true
console.log('Includes 6:', simpleArray.includes(6)); // false

// indexOf - find index of element
console.log('Index of 3:', simpleArray.indexOf(3)); // 2
console.log('Index of 6:', simpleArray.indexOf(6)); // -1

/**
 * EXAMPLE 12: Every and Some
 *
 * Test all or any elements.
 */

const scores = [85, 92, 78, 95, 88];

// every - all elements must pass
const allPassing = scores.every((score) => score >= 70);
console.log('All passing:', allPassing); // true

const allExcellent = scores.every((score) => score >= 90);
console.log('All excellent:', allExcellent); // false

// some - at least one element must pass
const someExcellent = scores.some((score) => score >= 90);
console.log('Some excellent:', someExcellent); // true

const someFailing = scores.some((score) => score < 70);
console.log('Some failing:', someFailing); // false

// Practical examples
const orders = [
  { id: 1, status: 'shipped' },
  { id: 2, status: 'pending' },
  { id: 3, status: 'shipped' },
];

const allShipped = orders.every((o) => o.status === 'shipped');
const anyPending = orders.some((o) => o.status === 'pending');
console.log('All shipped:', allShipped); // false
console.log('Any pending:', anyPending); // true

/**
 * EXAMPLE 13: Flat and FlatMap
 *
 * Flatten nested arrays.
 */

// flat - flatten nested arrays
const nestedArr = [1, [2, 3], [4, [5, 6]]];
console.log('Flat 1 level:', nestedArr.flat()); // [1, 2, 3, 4, [5, 6]]
console.log('Flat 2 levels:', nestedArr.flat(2)); // [1, 2, 3, 4, 5, 6]
console.log('Flat all:', nestedArr.flat(Infinity)); // [1, 2, 3, 4, 5, 6]

// flatMap - map + flat(1)
const sentences = ['Hello World', 'How are you'];
const wordsArr = sentences.flatMap((s) => s.split(' '));
console.log('Words:', wordsArr); // ['Hello', 'World', 'How', 'are', 'you']

// flatMap use case - expand items
const orders2 = [
  { id: 1, items: ['apple', 'banana'] },
  { id: 2, items: ['cherry'] },
];
const allItems = orders2.flatMap((order) => order.items);
console.log('All items:', allItems); // ['apple', 'banana', 'cherry']

/**
 * EXAMPLE 14: Array Destructuring
 *
 * Extract values from arrays.
 */

const rgb = [255, 128, 64];

// Basic destructuring
const [red, green, blue] = rgb;
console.log('RGB:', red, green, blue); // 255 128 64

// Skip elements
const [first, , third] = rgb;
console.log('First and third:', first, third); // 255 64

// Rest pattern
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log('Head:', head); // 1
console.log('Tail:', tail); // [2, 3, 4, 5]

// Default values
const [a = 0, b = 0, c = 0, d = 0] = [1, 2];
console.log('With defaults:', a, b, c, d); // 1 2 0 0

// Swap variables
let x = 1,
  y = 2;
[x, y] = [y, x];
console.log('Swapped:', x, y); // 2 1

// Nested destructuring
const matrix = [
  [1, 2],
  [3, 4],
];
const [[a1, a2], [b1, b2]] = matrix;
console.log('Matrix values:', a1, a2, b1, b2); // 1 2 3 4

/**
 * EXAMPLE 15: Spread Operator with Arrays
 *
 * Spread arrays into new contexts.
 */

const arr1a = [1, 2, 3];
const arr2a = [4, 5, 6];

// Combine arrays
const combined = [...arr1a, ...arr2a];
console.log('Combined:', combined); // [1, 2, 3, 4, 5, 6]

// Copy array (shallow)
const copy = [...arr1a];
console.log('Copy:', copy);

// Insert in middle
const middle = [...arr1a.slice(0, 2), 'x', ...arr1a.slice(2)];
console.log('Middle insert:', middle); // [1, 2, 'x', 3]

// Convert iterable to array
const chars = [...'hello'];
console.log('Chars:', chars); // ['h', 'e', 'l', 'l', 'o']

// Spread as function arguments
const numbersArr = [5, 2, 8, 1, 9];
console.log('Max:', Math.max(...numbersArr)); // 9
console.log('Min:', Math.min(...numbersArr)); // 1

/**
 * EXAMPLE 16: Common Patterns
 *
 * Frequently used array operations.
 */

// Remove duplicates
const withDupes = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(withDupes)];
console.log('Unique:', unique); // [1, 2, 3, 4]

// Get random element
const randomElement = (arr) => arr[Math.floor(Math.random() * arr.length)];
console.log('Random:', randomElement([1, 2, 3, 4, 5]));

// Create range
const createRange = (start, end) =>
  Array.from({ length: end - start + 1 }, (_, i) => start + i);
console.log('Range 1-5:', createRange(1, 5)); // [1, 2, 3, 4, 5]

// Chunk array
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
    arr.slice(i * size, i * size + size)
  );
console.log('Chunked:', chunk([1, 2, 3, 4, 5, 6, 7], 3));
// [[1, 2, 3], [4, 5, 6], [7]]

// Remove falsy values
const withFalsy = [0, 1, false, 2, '', 3, null, 4, undefined, 5];
const truthy = withFalsy.filter(Boolean);
console.log('Truthy:', truthy); // [1, 2, 3, 4, 5]

// Shuffle array (Fisher-Yates)
function shuffle(arr) {
  const result = [...arr];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}
console.log('Shuffled:', shuffle([1, 2, 3, 4, 5]));

console.log('\nArray examples completed!');
Examples - JavaScript Tutorial | DeepML