Arrays, objects, Map and Set
Arrays and their methods, sorting correctly, objects as records, and Map / Set.
Runs in Zerethon IDE · Node.js 22
Official JavaScript documentation ↗
main.js
const scores = [70, 95, 8, 82];
scores.push(60);
console.log(scores.length, scores[0], scores.at(-1));
console.log([...scores].sort()); // as text!
console.log([...scores].sort((a, b) => a - b)); // as numbers
console.log(scores.filter((s) => s >= 80).map((s) => s / 10));
console.log(scores.reduce((a, b) => a + b, 0), scores.includes(95));
const user = { name: 'Ada', langs: ['en'] };
const copy = { ...user, name: 'Grace' };
console.log(user.name, copy.name, Object.keys(copy));
const ages = new Map([['ada', 36]]);
ages.set('alan', 41);
console.log(ages.get('alan'), ages.has('linus'), ages.size);
console.log([...new Set([1, 1, 2, 3, 3])]);
const people = [{ name: 'bob', age: 25 }, { name: 'amy', age: 31 }];
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people.map((p) => p.name).join(', '));
Output
5 70 60 [ 60, 70, 8, 82, 95 ] [ 8, 60, 70, 82, 95 ] [ 9.5, 8.2 ] 315 true Ada Grace [ 'name', 'langs' ] 41 false 2 [ 1, 2, 3 ] amy, bob
Watch out: array.sort() without a compare function sorts values as strings, so 8 comes after 70. Pass (a, b) => a - b for numbers. sort() also changes the array in place — copy it first ([...array]) to keep the original.