Skip to content

Latest commit

 

History

History
136 lines (97 loc) · 2.34 KB

File metadata and controls

136 lines (97 loc) · 2.34 KB

JavaScript Arrays

JS Array

An array is an ordered collection.

const nums = [1, 2, 3];
const mixed = ["a", 1, true, null, { x: 1 }];

console.log(nums.length); // 3
console.log(nums[0]); // 1

Key points:

  • Arrays are objects (typeof [] === "object").
  • Indexes are 0-based.
  • length is mutable.
const a = [1, 2, 3];
a.length = 1;
console.log(a); // [1]

JS Array Methods

Common mutating vs non-mutating methods:

  • Non-mutating: slice, concat, map, filter, reduce, toSorted (newer)
  • Mutating: push, pop, shift, unshift, splice, sort, reverse
const a = [1, 2, 3];
const b = a.slice(0, 2);
console.log(a, b); // [1,2,3] [1,2]

a.splice(1, 1);
console.log(a); // [1,3]

Array Sort (Comparing Function)

Default sort() converts to strings, which can be surprising.

const n = [2, 10, 1];
n.sort();
console.log(n); // [1,10,2] (string compare)

Use a compare function for numeric sorting.

const n = [2, 10, 1];
n.sort((a, b) => a - b);
console.log(n); // [1,2,10]

Custom sorting objects:

const users = [
  { name: "A", age: 30 },
  { name: "B", age: 20 },
];

users.sort((u1, u2) => u1.age - u2.age);

For In Loop / For Of Loop

  • for...of iterates values (recommended for arrays).
  • for...in iterates enumerable keys (indexes) and can include unexpected properties.
const a = ["x", "y"];

for (const v of a) console.log(v); // x, y
for (const k in a) console.log(k); // 0, 1

Array map

Transform each element, returns a new array.

const a = [1, 2, 3];
const doubled = a.map((x) => x * 2);
console.log(doubled); // [2,4,6]

Array filter

Select elements by predicate.

const a = [1, 2, 3, 4];
const even = a.filter((x) => x % 2 === 0);
console.log(even); // [2,4]

Array reduce

Fold an array into a single value.

const a = [1, 2, 3];
const sum = a.reduce((acc, x) => acc + x, 0);
console.log(sum); // 6

Build objects with reduce:

const words = ["a", "b", "a"];
const counts = words.reduce((acc, w) => {
  acc[w] = (acc[w] ?? 0) + 1;
  return acc;
}, {});
console.log(counts); // { a: 2, b: 1 }

Array forEach

Use for side effects. It does not return a new array.

const a = [1, 2, 3];
a.forEach((x) => {
  console.log("value:", x);
});

Prefer map/filter/reduce when you want returned values.