1

I have a scenario like this , I get random values with key from an API request (around 100 per minute) , I need to do the following

  1. Push new items to the array
  2. Replace items if key is duplicate
  3. Sort the original Map and remove everything except last n elements in original array

I have following code , but it does not remove the original array but duplicates an array with last 2 elements.

      var stats = new Map([['22',10],['32',3],['42',22],['52',7]]);
   // I set dynamic values like below inside ajax function , can be duplicate or new
            stats.set('22', 20);
            stats.set('12', 20);
            // sort by key
            var keys = Array.from(stats.keys());
            keys.sort();
            // get the last two
            keys = keys.slice(-2);
            // map the remaining keys to the desired structure
            var result = keys.map(key => { 
              return { 
                key: key, 
                value: stats.get(key) 
              }; 
            });
            console.log(result); 

`

Gracie williams
  • 1,287
  • 2
  • 16
  • 39
  • 3
    Well, `keys.slice(0, -2).forEach(key => stats.delete(key))`? – Bergi May 08 '19 at 21:58
  • Still stats array has all items – Gracie williams May 08 '19 at 21:59
  • 1
    It would help if you were a little more precise with the language. What is the `original array` I see a `Map` at the beginning. Do you want a `Map` at the end or an `Array`? Right now you are creating an array of objects. Also you are sorting your keys which are strings. This means "152" sorts before "52" is that what you want? – Mark May 08 '19 at 22:09
  • 1
    @MarkMeyer the details of this question are unintentionally relying on information shared in [the previous question](https://stackoverflow.com/q/56048715/1541563). I agree that should be fixed. – Patrick Roberts May 08 '19 at 22:15
  • @PatrickRoberts : can you please check it , thank you. – Gracie williams May 08 '19 at 22:16
  • *"3. Sort the original Map"* `Map`s have a single order: the order their entries were inserted. They can't be sorted. If you want a different order, you'll need to create a new `Map`, remove and reinsert the entries, or use a different structure. – AuxTaco May 08 '19 at 22:48
  • It would be nice if you gave credit to where you got the code, like the license says you should... – Heretic Monkey May 08 '19 at 23:54
  • Can you please post the expected output result so that we know what needs to be done ? – dota2pro May 09 '19 at 14:52

1 Answers1

0

Copied @Bergi 's comment into code

var stats = new Map([['22',10],['32',3],['42',22],['52',7]]);
   // I set dynamic values like below inside ajax function , can be duplicate or new
            stats.set('22', 20);
            stats.set('12', 20);
            // sort by key
            var keys = Array.from(stats.keys());
            keys.sort();
            // get the last two
            keys = keys.slice(-2);
            // map the remaining keys to the desired structure
            keys.slice(0, -2).forEach(key => stats.delete(key))
            stats = keys.map(key => { 
              return { 
                key: key, 
                value: stats.get(key) 
              }; 
            });
            
            console.log(stats);
dota2pro
  • 7,220
  • 7
  • 44
  • 79
  • When I do stats.set('12', 20); again ,I get this error stats.set is not a function – Gracie williams May 08 '19 at 22:01
  • Are you using chrome ? what browser are you using ? you can run the code here click on the Run code Snippet button – dota2pro May 08 '19 at 22:02
  • I mean your code runs fine , after that when i need to push new values , i am unable to set. – Gracie williams May 08 '19 at 22:03
  • 1
    @dota2pro The `forEach` line mutates `stats`. There's no need to redefine it afterwards. – AuxTaco May 08 '19 at 22:04
  • 1
    ...no. `keys.sort();`, then `keys.slice(0, -2).forEach(key => stats.delete(key));`. That's it. Nothing else required. – AuxTaco May 08 '19 at 22:06
  • @AuxTaco that prints an empty array for me – dota2pro May 08 '19 at 22:07
  • Bug in the snippet console. Check the browser console. Or `console.log([...stats.entries()])`. – AuxTaco May 08 '19 at 22:11
  • @AuxTaco , why did u use keys.slice(0, -2) , instead keys.slice(0,keys.length-2), I am looking for last 2 elements only. – Gracie williams May 08 '19 at 22:22
  • @Graciewilliams `keys.slice(0, -2)` is everything *except* the last two elements; `.forEach(key => stats.delete(key))` deletes them. `stats` minus (everything except the last two elements of `stats`) equals (the last two elements of `stats`). – AuxTaco May 08 '19 at 22:34
  • What if I have only 2 elements in starting ? Its not running foreach and its not sorting – Gracie williams May 08 '19 at 22:35
  • @AuxTaco : no ur solution is deleting items in original array , but its not sorting – Gracie williams May 08 '19 at 22:42
  • Note that this answer redefines `stats` such that it is no longer a `Map`; it is an array of objects. @Graciewilliams that's why `set` does not work. But your original question wanted the results in a specific structure that wasn't the original structure. You need to decide if you still want the original structure (i.e., a `Map` with keys and values, an array of objects with string keys and numeric values, or whatever) or you want the new structure (an array of objects with `key` and `value` properties). – Heretic Monkey May 09 '19 at 00:01
  • @HereticMonkey : I want original structure , how to do it ? – Gracie williams May 09 '19 at 04:39
  • Placing my code after `keys = keys.slice(-2);` won't work as intended – Bergi May 09 '19 at 06:36