JS: Truncate Map 📜

By Xah Lee. Date: . Last updated: .

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