Add, remove and sort Map entries
MediumMap and Set10 min
Write a function applyChanges(initial, toAdd, toRemove) that changes a map in three steps and returns its entries sorted by key.
initialandtoAddare arrays of pairs[key, value]. The key is a string, the value is a number. Keys insideinitialare unique, keys insidetoAddare unique too.toRemoveis an array of keys.- Step 1: create a
Mapfrominitial. - Step 2: add every pair of
toAdd. If the key is already in the map, it gets the new value. - Step 3: delete every key of
toRemovefrom the map. A key that is not in the map is ignored. - Return a new array of
[key, value]pairs, sorted by key. Compare keys as plain strings, the waysort()with no compare function orders strings: capital letters come before small letters, and a key comes before a longer key that starts with it. So'Banana'comes before'apple', and'item'comes before'item 2'. - Keys can contain capital letters and spaces. Any of the three arrays can be empty. If the map is empty at the end, return
[].
Examples
applyChanges([['pear', 3], ['apple', 5]], [['kiwi', 2], ['apple', 7]], ['pear'])Returns [ [ 'apple', 7 ], [ 'kiwi', 2 ] ]
applyChanges([['cherry', 1], ['Banana', 2], ['apple', 3]], [], [])Returns [ [ 'Banana', 2 ], [ 'apple', 3 ], [ 'cherry', 1 ] ]
Asked at Accion Labs · Source
Loading the editor...
- Input
applyChanges([ [ 'pear', 3 ], [ 'apple', 5 ] ], [ [ 'kiwi', 2 ] ], [ 'pear' ])Expected[ [ 'apple', 5 ], [ 'kiwi', 2 ] ] - Input
applyChanges([ [ 'cherry', 1 ], [ 'banana', 2 ], [ 'apple', 3 ] ], [], [])Expected[ [ 'apple', 3 ], [ 'banana', 2 ], [ 'cherry', 1 ] ] - Input
applyChanges([ [ 'apple', 5 ], [ 'pear', 1 ] ], [ [ 'apple', 7 ] ], [])Expected[ [ 'apple', 7 ], [ 'pear', 1 ] ]
Hidden tests run on Submit