JavaScript Advanced Day 3: Advanced Arrays & Iterators

Goal of this Day

Today you will learn:

By the end, you will manipulate complex data structures with ease.

Step 1: Advanced Array Methods

Using find, some, every:


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

console.log(numbers.find(n => n > 3)); // 4
console.log(numbers.some(n => n > 4)); // true
console.log(numbers.every(n => n > 0)); // true

Step 2: Generators

Generators yield values lazily:


function* idGenerator() {
  let id = 1;
  while(true) yield id++;
}

const gen = idGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

Step 3: Reduce for Deep Operations

Flatten nested arrays using reduce:


const nested = [[1,2], [3,4], [5]];
const flat = nested.reduce((acc, val) => acc.concat(val), []);
console.log(flat); // [1,2,3,4,5]

Practice


function* idGenerator() {
  let id = 1;
  while(true) yield id++;
}

const gen = idGenerator();
console.log(gen.next().value);
console.log(gen.next().value);

Task

Complete the following:

Example:


// Generator for even numbers
function* evenNumbers() {
  let n = 2;
  while(true) yield n, n += 2;
}

const evGen = evenNumbers();
console.log(evGen.next().value); // 2
console.log(evGen.next().value); // 4

// Flatten nested array
const nested = [[1,2],[3,4],[5]];
const flat = nested.reduce((acc, val) => acc.concat(val), []);
console.log(flat); // [1,2,3,4,5]