appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Arrays and objects

Lesson 2 of 310 minBeginner

Store collections and transform them with map, filter and reduce.

const fruits = ["apple", "pear"];
fruits.push("plum");
console.log(fruits[0], fruits.length);   // apple 3

const user = { name: "Ana", age: 31 };
console.log(user.name, user["age"]);
user.country = "ES";

map, filter, reduce

const nums = [1, 2, 3, 4];
const doubled = nums.map((n) => n * 2);          // [2, 4, 6, 8]
const evens = nums.filter((n) => n % 2 === 0);   // [2, 4]
const sum = nums.reduce((a, n) => a + n, 0);     // 10

These methods return new arrays and leave the original unchanged, which keeps code easier to follow.

Destructuring and spread

const { name, age } = user;
const more = [...fruits, "kiwi"];
const copy = { ...user, age: 32 };

JSON

const text = JSON.stringify(user);   // object to string
const back = JSON.parse(text);       // string to object

NoteJSON is the common format for sending data between servers and browsers. Keys and strings must use double quotes.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does [1,2,3].map((n) => n * 2) return?
2. Which method keeps only the items that pass a test?
3. What converts an object to a JSON string?
HintAn array method that pushes.

Key terms