Best way to create a hashmap in ES6 with number as index
Ad
I want to build an hashmap class, or use one that comes with the language.
The index are integers. If I try to do this with an array, I see on the debugger than the size of the array is equals to the higher integer key.
Ie, if my hashmap has two elements, Map[0]= 'word1'
and Map[1023]= 'word2'
I can see that the array has size 1024.
I'd prefer not to waste so much space.
I can't make any assumption on how the keys are distributed.
Ad
Answer
Ad
ECMAScript 6 introduces a true Map type which can be used as follows:
const m = new Map();
m.set(0, "word1");
m.set(1023, "word2");
for(const [key, value] of m) {
console.log(key, value, typeof key);
}
Note how key
is still a number - using an object literal, keys are always strings. It also provides a size
property for counting key/value pairs:
const m = new Map();
m.set(0, "word1");
m.set(1023, "word2");
console.log(m.size); // 2
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad