𝗔𝗿𝗿𝗮𝘆𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Arrays store multiple values in one variable. They keep data organized in a specific order.
Without arrays, you must create separate variables for every item. This becomes hard to manage as your data grows. With arrays, you group everything together.
Common uses for arrays:
- Lists of student names
- Product lists
- Shopping cart items
- Mobile numbers
How arrays work: Arrays use indexes to find items. The first item is always at index 0.
Example: let fruits = ["Apple", "Banana", "Orange"];
- fruits[0] is "Apple"
- fruits[1] is "Banana"
- fruits[2] is "Orange"
Essential Array Methods:
Adding and Removing:
- push(): Add item to the end.
- pop(): Remove item from the end.
- unshift(): Add item to the start.
- shift(): Remove item from the start.
- splice(): Add or remove items at any position.
Extracting and Searching:
- slice(): Copy a part of the array.
- indexOf(): Find the position of an item.
- includes(): Check if an item exists.
- find(): Return the first item that matches a condition.
Transforming Data:
- map(): Change every item in the array.
- filter(): Keep only items that meet a condition.
- reduce(): Combine all items into one single value.
- sort(): Put items in order.
- reverse(): Flip the order of items.
Array vs. Object:
- Arrays use numbers (indexes) to find data. They are best for lists.
- Objects use keys to find data. They are best for describing one entity.
Example:
- Array: ["Red", "Blue", "Green"]
- Object: { color: "Red", id: 1 }
Master these methods to handle data efficiently in your code.
Source: https://www.geeksforgeeks.org/javascript/javascript-arrays/ Source: https://www.w3schools.com/js/js_arrays.asp
Full guide: https://dev.to/annapoo/arrays-in-javascript-2nb4