Advanced Array & Object Transformations
Published by Brayan K
Array and object transformations are techniques for reshaping data using methods like map, filter, and reduce to convert, combine, and restructure collections without mutating the originals.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Choose an output shape before choosing a method
A transform needs a contract: what one input row means, which rows are accepted, how duplicate keys combine and what order the result uses. Chaining familiar methods does not answer those questions. We will build a stock summary from fixed records, then test empty input, malformed rows and keys that ordinary object grouping often mishandles.
const rows = [
{ warehouse: "west", units: 3 },
{ warehouse: "east", units: 2 },
{ warehouse: "west", units: 4 }
];
const totals = new Map(); // Keys are warehouse names, values are running totals.
for (const row of rows) {
totals.set(row.warehouse, (totals.get(row.warehouse) ?? 0) + row.units);
}
const report = [...totals].map(([warehouse, units]) => ({ warehouse, units }));
console.log(JSON.stringify(report)); // Convert the builder into the promised output shape.
console.log(rows.length, rows[0].units);
// ✅ Expected output:
// [{"warehouse":"west","units":7},{"warehouse":"east","units":2}]
// 3 3The input here is already validated. The Map preserves first insertion order, while repeated keys accumulate rather than overwrite. It is a fresh local builder, so updating it does not change the input records. map, filter & reduce owns the basic callback methods; this lesson owns multi-stage shape, aggregation and collision policies.
An accumulator must survive every callback
console.log([].reduce((total, value) => total + value, 0));
const visits = [];
const total = [4, 6].reduce((sum, value, index) => {
visits.push(index);
return sum + value;
}, 0);
console.log(total, visits.join(","));
// ✅ Expected output:
// 0
// 10 0,1console.log([].reduce((sum, value) => sum + value));
// ✅ Expected error:
// TypeError: Reduce of empty array with no initial valueconst result = ["A", "B"].reduce((groups, key) => {
groups[key] = 1;
}, {});
console.log(result);
// ✅ Expected error:
// TypeError: Cannot set properties of undefined (setting 'B')The first callback returns undefined, so the second tries to write a property on undefined. A corrected reducer must return its accumulator. A loop is often clearer when aggregation needs validation, multiple fields or early exits; using reduce is not a quality requirement.
const sparse = [2, , 4];
const visited = [];
sparse.reduce((sum, value, index) => {
visited.push(index);
return sum + value;
}, 0);
console.log(visited.join(","));
console.log(Array.from(sparse).map(value => String(value)).join("|"));
// ✅ Expected output:
// 0,2
// 2|undefined|4Array iteration methods such as reduce skip holes. Array.from makes this sparse input dense, with undefined at the missing position. Decide whether a missing row is invalid instead of accidentally dropping it during validation. The final brief uses indexed reads to reject holes.
Flatten exactly the level your output requires
const values = [1, [2, [3]], 4];
console.log(JSON.stringify(values.flat()));
console.log(JSON.stringify(values.flat(2)));
console.log(JSON.stringify(values));
// ✅ Expected output:
// [1,2,[3],4]
// [1,2,3,4]
// [1,[2,[3]],4]const rows = [
{ id: "A", tags: ["fast", "small"] },
{ id: "B", tags: [] },
{ id: "C", tags: ["quiet"] }
];
const pairs = rows.flatMap(row => row.tags.map(tag => ({ id: row.id, tag })));
console.log(JSON.stringify(pairs));
console.log(JSON.stringify([1, 2].flatMap(value => [[value, value * 10]])));
// ✅ Expected output:
// [{"id":"A","tag":"fast"},{"id":"A","tag":"small"},{"id":"C","tag":"quiet"}]
// [[1,10],[2,20]]The empty tag array contributes no pair. The second example deliberately returns a nested array: flatMap removes one level, leaving each pair intact. Flattening changes structure, not ownership; retained objects still refer to the same records. Deep Copy vs Shallow Copy & Data Structures owns complete supported-graph cloning.
Entries are a view, not a lossless record format
const secret = Symbol("secret");
const source = Object.create({ inherited: 1 });
source.visible = 2;
source[secret] = 3;
Object.defineProperty(source, "hidden", { value: 4 });
console.log(JSON.stringify(Object.entries(source)));
console.log(Reflect.ownKeys(source).length);
// ✅ Expected output:
// [["visible",2]]
// 3const renamed = Object.fromEntries([["score", 2], ["score", 8]]);
console.log(renamed.score);
const numeric = Object.fromEntries([[1, "number"], ["1", "string"]]);
console.log(Object.keys(numeric).length, numeric["1"]);
const preserved = new Map([[1, "number"], ["1", "string"]]);
console.log(preserved.size, preserved.get(1), preserved.get("1"));
// ✅ Expected output:
// 8
// 1 string
// 2 number stringRenaming keys can create collisions even if the original keys were unique. Object property keys convert numbers to strings; Map keeps the number and string distinct. Choose overwrite, reject or aggregate deliberately. Rebuilding from entries also does not preserve descriptors or a custom prototype. Object Methods (keys, entries, assign, freeze) owns property APIs.
const entries = [["10", "ten"], ["2", "two"], ["west", "W"]];
console.log([...new Map(entries).keys()].join(","));
console.log(Object.keys(Object.fromEntries(entries)).join(","));
// ✅ Expected output:
// 10,2,west
// 2,10,westIf report order matters, return an array or specify an explicit sort. Do not infer first-seen report order from Object.keys on numeric-looking property names.
Grouping must handle ordinary data that resembles an inherited name
const groups = new Map();
for (const key of ["constructor", "__proto__", "constructor"]) {
groups.set(key, (groups.get(key) ?? 0) + 1);
}
console.log(JSON.stringify([...groups]));
const record = Object.fromEntries([["__proto__", 7]]);
console.log(Object.hasOwn(record, "__proto__"), record.__proto__);
console.log(Object.getPrototypeOf(record) === Object.prototype);
// ✅ Expected output:
// [["constructor",2],["__proto__",1]]
// true 7
// trueA plain object lookup can find an inherited property when a grouping algorithm expects an empty bucket. Map avoids that inherited-name ambiguity. Object.fromEntries creates its __proto__ entry as an own data property here; this does not make every assignment-based merge safe for untrusted keys. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns broader input and trust boundaries.
Reject bad rows explicitly instead of quietly repairing their meaning
function units(value) {
if (!Number.isSafeInteger(value) || value < 0) throw new TypeError("units must be a non-negative safe integer");
return value;
}
for (const value of [0, 3, "3", -1, NaN]) {
try { console.log("accepted", units(value)); }
catch (error) { console.log(error.name, error.message); }
}
console.log([0, 3].filter(Boolean).join(","));
// ✅ Expected output:
// accepted 0
// accepted 3
// TypeError units must be a non-negative safe integer
// TypeError units must be a non-negative safe integer
// TypeError units must be a non-negative safe integer
// 3A truthiness filter loses valid zero. Number conversion would accept strings that this contract rejects. Neither choice is inherently universal; specify it before transforming. For tolerant imports, keep rejected row indices and reasons rather than silently changing them into zero. Integer inputs can still overflow when summed; the final brief checks each new total.
Guided exercise: expand order lines into report rows
Fill the literal hints. Produce one output per line, retain the order id, and let an order with no lines contribute no rows.
const orders = [
{ id: "A", lines: [{ sku: "pen", quantity: 2 }, { sku: "book", quantity: 1 }] },
{ id: "B", lines: [] }
];
const rows = orders.___(order => // 👉 replace ___ with flatMap
order.lines.map(line => ({
order: order.___, // 👉 replace ___ with id
sku: line.sku,
quantity: line.quantity
}))
);
console.log(JSON.___(rows)); // 👉 replace ___ with stringify
// ✅ Expected output:
// [{"order":"A","sku":"pen","quantity":2},{"order":"A","sku":"book","quantity":1}]Independent brief: a validated warehouse and SKU report
Write stockReport(rows) for a dense array of plain records with warehouse and sku strings and a units number. Trim both names, reject empty names, and require non-negative safe-integer units. Aggregate by the pair of names, keeping warehouses and each warehouse’s SKUs in first-seen order. A literal separator inside a name must not merge two different pairs. Check every addition for safe-integer overflow.
Return an array of records shaped as warehouse, totalUnits and items, where each item has sku and units. Preserve zero-unit entries. Reject malformed records and holes, leave inputs unchanged, and return fresh output records. Check empty input, duplicates, trimmed names, constructor/__proto__, two pairs that collide under naive string joining, invalid units and overflow.
function stockReport(rows) {
if (!Array.isArray(rows)) throw new TypeError("rows must be an array");
const warehouses = new Map();
for (let index = 0; index < rows.length; index++) {
const row = rows[index];
if (row === null || typeof row !== "object" || Array.isArray(row) ||
Object.getPrototypeOf(row) !== Object.prototype) {
throw new TypeError("each row must be a plain record");
}
if (typeof row.warehouse !== "string" || typeof row.sku !== "string" ||
row.warehouse.trim() === "" || row.sku.trim() === "") {
throw new TypeError("warehouse and sku must be non-empty strings");
}
if (!Number.isSafeInteger(row.units) || row.units < 0) {
throw new TypeError("units must be a non-negative safe integer");
}
const warehouse = row.warehouse.trim(), sku = row.sku.trim();
let group = warehouses.get(warehouse);
if (!group) { group = { totalUnits: 0, items: new Map() }; warehouses.set(warehouse, group); }
const units = (group.items.get(sku) ?? 0) + row.units;
const total = group.totalUnits + row.units;
if (!Number.isSafeInteger(units) || !Number.isSafeInteger(total)) {
throw new RangeError("stock total exceeds safe integer range");
}
group.items.set(sku, units);
group.totalUnits = total;
}
return [...warehouses].map(([warehouse, group]) => ({
warehouse, totalUnits: group.totalUnits,
items: [...group.items].map(([sku, units]) => ({ sku, units }))
}));
}
const rows = [
{ warehouse: " west ", sku: "pen", units: 0 },
{ warehouse: "east", sku: "book", units: 2 },
{ warehouse: "west", sku: "pen", units: 3 },
{ warehouse: "west", sku: "book", units: 1 }
];
const before = JSON.stringify(rows);
console.log(JSON.stringify(stockReport(rows)));
console.log(JSON.stringify(stockReport([])), JSON.stringify(rows) === before);
console.log(JSON.stringify(stockReport([
{ warehouse: "a|b", sku: "c", units: 1 },
{ warehouse: "a", sku: "b|c", units: 2 },
{ warehouse: "__proto__", sku: "constructor", units: 0 }
])));
for (const input of [
[undefined], new Array(1),
[{ warehouse: " ", sku: "pen", units: 1 }],
[{ warehouse: "west", sku: "pen", units: "2" }],
[{ warehouse: "west", sku: "pen", units: Number.MAX_SAFE_INTEGER },
{ warehouse: "west", sku: "book", units: 1 }]
]) {
try { stockReport(input); } catch (error) { console.log(error.name, error.message); }
}
const output = stockReport(rows);
output[0].items[0].units = 99;
console.log(rows[0].units);
// ✅ Expected output:
// [{"warehouse":"west","totalUnits":4,"items":[{"sku":"pen","units":3},{"sku":"book","units":1}]},{"warehouse":"east","totalUnits":2,"items":[{"sku":"book","units":2}]}]
// [] true
// [{"warehouse":"a|b","totalUnits":1,"items":[{"sku":"c","units":1}]},{"warehouse":"a","totalUnits":2,"items":[{"sku":"b|c","units":2}]},{"warehouse":"__proto__","totalUnits":0,"items":[{"sku":"constructor","units":0}]}]
// TypeError each row must be a plain record
// TypeError each row must be a plain record
// TypeError warehouse and sku must be non-empty strings
// TypeError units must be a non-negative safe integer
// RangeError stock total exceeds safe integer range
// 0Reference notes
The reduce reference documents initial values, callback return values and holes. The flatMap reference defines its single flattening level. These examples check shapes, values and ownership; they make no measured speed claim.
Practice quiz
What does this complete program print? console.log([].reduce((sum,n)=>sum+n,10));
- 10
- 0
- undefined
- TypeError
Answer: 10. The initial accumulator is the result when no callback runs.
What does this complete program print? const visits=[];[2,,4].reduce((sum,n,i)=>{visits.push(i);return sum+n},0);console.log(visits.join(","));
- 0,1,2
- 0,2
- 1,2
- 0,2,3
Answer: 0,2. The empty slot is skipped by reduce.
What does this complete program print? console.log(JSON.stringify([1,2].flatMap(n=>[[n,n*2]])));
- [1,2,2,4]
- [[[1,2]],[[2,4]]]
- [[1,2],[2,4]]
- [2,4]
Answer: [[1,2],[2,4]]. Only one wrapping level is removed.
What does this complete program print? console.log(Object.fromEntries([["a",1],["a",7]]).a);
- 1
- 2
- undefined
- 7
Answer: 7. The later entry replaces the same own property.
What does this complete program print? const value=Object.create({a:1});value.b=2;console.log(Object.entries(value).map(([key])=>key).join(","));
- b
- a,b
- a
- b,a
Answer: b. Only the own enumerable string property is included.
What does this complete program print? console.log(new Map([[1,"number"],["1","string"]]).size);
- 1
- 2
- 0
- TypeError
Answer: 2. Map distinguishes numeric and string keys.
What does this complete program print? console.log(Object.keys(Object.fromEntries([["10",1],["2",2],["z",3]])).join(","));
- 10,2,z
- z,10,2
- 2,10,z
- 2,z,10
Answer: 2,10,z. Integer-index keys enumerate numerically before the other string key.
What does this complete program print? const source=[{units:2}];const flat=[source].flat();flat[0].units=9;console.log(source[0].units,flat===source);
- 2 false
- 9 true
- 2 true
- 9 false
Answer: 9 false. Flattening creates an outer array but retains the record reference.
Continue this course
- Previous: Deep Copy vs Shallow Copy & Data Structures
- Next: Custom Event Emitters & Observer Pattern — Build your own event system and implement the observer pattern from scratch
- Quick reference: JavaScript cheat sheet
- From the blog: Array Methods in JavaScript You Must Know