Arrays and ObjectsLesson 4.1
JavaScript Arrays: Creating and Manipulating Data Lists
array creation, indexing, push, pop, shift, unshift, splice, slice, spread, Array methods: map, filter, reduce, find, forEach
JavaScript Arrays: Creating and Manipulating Data Lists
Arrays are ordered collections of values. They are one of the most frequently used data structures in JavaScript, used for everything from storing a list of users to processing API responses. JavaScript arrays are dynamic โ they can hold any type of value and grow or shrink as needed.
Creating Arrays
const fruits = ['apple', 'banana', 'cherry'];
const numbers = [1, 2, 3, 4, 5];
const mixed = ['hello', 42, true, null];
const empty = [];Accessing and Modifying Elements
const colours = ['red', 'green', 'blue'];
console.log(colours[0]); // 'red'
console.log(colours.length); // 3
colours[1] = 'yellow';
console.log(colours); // ['red', 'yellow', 'blue']Adding and Removing Elements
const items = ['a', 'b', 'c'];
items.push('d'); // add to end
items.unshift('z'); // add to beginning
console.log(items); // ['z', 'a', 'b', 'c', 'd']
items.pop(); // remove from end
items.shift(); // remove from beginning
console.log(items); // ['a', 'b', 'c']Transforming Arrays: map, filter, reduce
const prices = [10, 25, 30, 15, 50];
// map โ transform each element
const doubled = prices.map(price => price * 2);
console.log(doubled); // [20, 50, 60, 30, 100]
// filter โ keep matching elements
const expensive = prices.filter(price => price > 20);
console.log(expensive); // [25, 30, 50]
// reduce โ accumulate to single value
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 130Finding and Searching
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const bob = users.find(user => user.name === 'Bob');
console.log(bob); // { id: 2, name: 'Bob' }
const hasCharlie = users.some(user => user.name === 'Charlie');
console.log(hasCharlie); // true