Map entries Spread And Rebuild Roundtrip
Spreading map.entries() yields typed tuple arrays that sort and filter like normal arrays, and new Map(entries) rebuilds with insertion order restored.
Code
const stock: ReadonlyMap<string, number> = new Map([
['coffee', 320],
['tea', 280],
['cocoa', 450],
]);
// entries() 展开成元组数组:可以像普通数组一样排序
const entries: ReadonlyArray<readonly [string, number]> = [...stock.entries()];
console.log(JSON.stringify(entries), 'sorted-by-value:', JSON.stringify([...entries].sort((a, b) => a[1] - b[1])));
// 元组数组重建 Map:键序按数组顺序重排,get 与 size 保持不变
const rebuilt = new Map(entries);
console.log(rebuilt.get('coffee'), rebuilt.size);Output
Captured from a sandboxed run of this snippet in the build pipeline.
[["coffee",320],["tea",280],["cocoa",450]] sorted-by-value: [["tea",280],["coffee",320],["cocoa",450]]
320 3Inside the execution
Everything operates on top-level bindings: rebuilt.
Caveats
- Its surface is entirely internal: standard library supplies every behavior.
Core lines
const rebuilt = new Map(entries);
const stock: ReadonlyMap<string, number> = new Map([
['coffee', 320],
['tea', 280],
['cocoa', 450],
]);
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `rebuilt`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.