Lessons in this course (16)

4. Arrays and objects — the essential methods

Basic★ Must knowLesson 4 of 16
js
const orders = [
  { id: 1, customer: "Asha", total: 1200, status: "paid" },
  { id: 2, customer: "Ravi", total: 300, status: "pending" },
  { id: 3, customer: "Asha", total: 450, status: "paid" },
];

orders.map(o => o.total);                          // [1200, 300, 450]
orders.filter(o => o.status === "paid");           // 2 items
orders.reduce((sum, o) => sum + o.total, 0);       // 1950
orders.find(o => o.id === 2);                      // object or undefined
orders.findIndex(o => o.id === 2);                 // 1
orders.some(o => o.total > 1000);                  // true
orders.every(o => o.total > 100);                  // true
orders.forEach(o => console.log(o.id));            // returns undefined
[3, 1, 2].sort((a, b) => a - b);                   // MUTATES; default sort is by string!
[3, 1, 2].toSorted((a, b) => a - b);               // non-mutating (ES2023)
[[1, 2], [3]].flat();                              // [1, 2, 3]
Object.groupBy(orders, o => o.customer);           // { Asha: [...], Ravi: [...] } (ES2024)
orders.at(-1);                                     // last item

// Mutating: push, pop, shift, unshift, splice, sort, reverse, fill
// Non-mutating: map, filter, slice, concat, toSorted, toReversed, toSpliced, with

// Objects
const { customer, total = 0, ...rest } = orders[0];   // destructuring with default + rest
Object.keys(obj); Object.values(obj); Object.entries(obj);
Object.fromEntries([["a", 1]]);
structuredClone(obj);                                // deep copy (no functions)
user?.address?.city ?? "Unknown";                    // optional chaining + nullish coalescing

?? falls back only on null/undefined; || falls back on any falsy value (0 || 10 → 10, 0 ?? 10 → 0).