JS: Truncate Map 📜
Here's a function that return a new map, containing only first n entries.
/* return a new map, containing only first n entries. http://xahlee.info/js/js_map_truncate.html Created: 2021-05-08 Version: 2026-01-22 */ // const xah_truncate_map = (mapObj, n) => new Map(Array.from(mapObj.entries()).slice(0, n)); const xah_truncate_map = (mapObj, n) => { if (n >= mapObj.size) return new Map(mapObj); const xout = new Map(); let xcount = 0; for (const [key, value] of mapObj) { xout.set(key, value); xcount++; if (xcount >= n) break; } return xout; }; // s------------------------------ // test const xx = new Map([[3, 3], [4, 4], [5, 5]]); console.log(xah_truncate_map(xx, 2)); // Map(2) { 3 => 3, 4 => 4 }
JavaScript. Map Object
- JS: Map (dictionary)
- JS: Difference, Object vs Map
- JS: Literal Expression for Map
- JS: Nested Map
- JS: Iterate Map Object
- JS: Convert Object to Map 📜
- JS: Convert Map to Object 📜
- JS: Test Equality of Map Objects 📜
- JS: Map Filter 📜
- JS: Swap Key Value of Map 📜
- JS: Sort Map 📜
- JS: Truncate Map 📜
- JS: Map Substract 📜
- JS: How Map Determines Uniqueness of Keys
- JS: Map (class)
- JS: Map Constructor
- JS: Map.prototype