Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
map-prototype-sort.js: Array.prototype.sort 互換のメソッドを定義



Map.prototype.sortArray.prototype.sort 互換のメソッドを定義します。



第一引数に指定された比較関数を基準として、ソートした Map オブジェクトを返します。

var map = new Map([['a',2],['b',1],['c',3]]).sort((a,b) => a[1] - b[1]);

console.log(JSON.stringify([]));	// [["b",1],["a",2],["c",3]]

Map.prototype.sort は破壊的です。

var map = new Map([[3, 'c'],[2, 'b'],[4, 'd'],[1, 'a']]);

map.sort((a,b) => a[0] - b[0]);
console.log(JSON.stringify([]));	// [[1,"a"],[2,"b"],[3,"c"],[4,"d"]]
* map-prototype-sort-1.0.0.js
* Sort map object.
* @version 1.0.0
* @author think49
* @url
* @license (The MIT License)
if (typeof Map === 'function' && !('sort' in Map.prototype) && typeof Object.defineProperties === 'function') {
Object.defineProperties(Map.prototype, {sort: {
writable: true,
enumerable: false,
configurable: true,
value: function sort (comparefn) {
var entries = [...this.entries()].sort(comparefn);
for (let [key, value] of entries) {
this.set(key, value);
return this;
<!DOCTYPE html>
<script src="map-prototype-sort-1.0.0.js"></script>
'use strict';
console.assert(JSON.stringify([ Map([['a',2],['b',1],['c',3]]).sort((a,b) => a[1] - b[1])]) === '[["b",1],["a",2],["c",3]]');
var map = new Map([[3, 'c'],[2, 'b'],[4, 'd'],[1, 'a']]);
map.sort((a,b) => a[0] - b[0]);
console.assert(JSON.stringify([]) === '[[1,"a"],[2,"b"],[3,"c"],[4,"d"]]');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.