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 inList
, which describes the contents of the Map. – VLAZ Commented May 22, 2019 at 15:21
1 Answer
Reset to default 13A 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
版权声明:本文标题:Javascript does there is a nice way to 'slice' a map - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740198372a2239747.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论