admin管理员组

文章数量:1246007

I'm aware of slice() for arrays, right now to 'slice' a map I am using this code :

const map = new Map([[1,"a"],[2,"b"]])

var arrayTmp = Array.from(map).slice(0,1);

var myMap = new Map();
arrayTmp.forEach(value => {
   myMap.set(value[0], value[1]); 
});

It works correctly, but I was wondering if there was some existing native methods to get a more concise code?

I'm aware of slice() for arrays, right now to 'slice' a map I am using this code :

const map = new Map([[1,"a"],[2,"b"]])

var arrayTmp = Array.from(map).slice(0,1);

var myMap = new Map();
arrayTmp.forEach(value => {
   myMap.set(value[0], value[1]); 
});

It works correctly, but I was wondering if there was some existing native methods to get a more concise code?

Share Improve this question asked May 22, 2019 at 15:04 Logan WlvLogan Wlv 3,7447 gold badges34 silver badges61 bronze badges 8
  • Keys in Map should be unordered - how do you going to slice it? – RidgeA Commented May 22, 2019 at 15:07
  • 1 @RidgeA think you are thinking of an object not a Map, maps are ordered: "The Map object holds key-value pairs and remembers the original insertion order of the keys." developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – atmd Commented May 22, 2019 at 15:08
  • Would an array not work better here? Maps aren't indexed so slicing will mean a fair amount of iteration, I think – OliverRadini Commented May 22, 2019 at 15:11
  • 1 @atmd object keys are ordered in ES6+ – p.s.w.g Commented May 22, 2019 at 15:12
  • 1 @RidgeA the specifications do not say "store the insertion order of keys" at the top, however, if you check the .forEach section iteration is explicitly described as happening in insertion order. Moreover, further down for .set, the steps also explicitly say that the new entry should the the last one in List, which describes the contents of the Map. – VLAZ Commented May 22, 2019 at 15:21
 |  Show 3 more ments

1 Answer 1

Reset to default 13

A Map stores the key/value pairs in insertation order.

You could omit the iteration and take just the sliced array as parameter for the constructor.

const
    map = new Map([[1, "a"], [2, "b"]]);
    arrayTmp = Array.from(map).slice(0, 1),
    myMap = new Map(arrayTmp),

console.log([...myMap]);

本文标签: Javascript does there is a nice way to 39slice39 a mapStack Overflow