0

I have json objects stored in a javascript Map. These items are ordered in according to how they were added to the Map.

var rows =  new Map();

rows.set(1, A);
rows.set(3, B);
rows.set(4, C);
rows.set(7, D);
// A, B, C, D

Now I would like to move an object up or down one position, is there a way to do this.

rows.swap(1, 3);
// B, A, C, D
knatz
  • 41
  • 1
  • 8
  • You should not use a `Map` if you want to set a specific order. – Bergi May 27 '18 at 16:22
  • Possible duplicate of [Is it possible to sort a ES6 map object?](https://stackoverflow.com/q/31158902/1048572) – Bergi May 27 '18 at 16:24
  • I don't want to Sort the items. I only want to change the order of max 2 items – knatz May 27 '18 at 20:01
  • It's the same issue - maps don't support this kind of operation. – Bergi May 27 '18 at 20:53
  • Does this answer your question? [Is it possible to sort a ES6 map object?](https://stackoverflow.com/questions/31158902/is-it-possible-to-sort-a-es6-map-object) – Inigo Mar 17 '22 at 15:54

1 Answers1

1

Disclaimer

Why is extending native objects a bad practice?

Oherwise an array is the best data structure for reordering items.

You need to delete all key/value pairs and assign new ordered items to this.

Map.prototype.swap = function (a, b) {
    var all = [...this],
        indexA = all.findIndex(([v]) => v === a),
        indexB = all.findIndex(([v]) => v === b);
    
    [all[indexA], all[indexB]] = [all[indexB], all[indexA]];
    this.forEach((_, k, m) => m.delete(k));
    all.forEach(([k, v]) => this.set(k, v));
}

var rows =  new Map;

rows.set(1, 'A');
rows.set(3, 'B');
rows.set(4, 'C');
rows.set(7, 'D');

rows.swap(1, 3);

console.log([...rows]);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392