Code Lab

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.

  • initial and toAdd are arrays of pairs [key, value]. The key is a string, the value is a number. Keys inside initial are unique, keys inside toAdd are unique too.
  • toRemove is an array of keys.
  • Step 1: create a Map from initial.
  • 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 toRemove from 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 way sort() 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...
  1. InputapplyChanges([ [ 'pear', 3 ], [ 'apple', 5 ] ], [ [ 'kiwi', 2 ] ], [ 'pear' ])
    Expected[ [ 'apple', 5 ], [ 'kiwi', 2 ] ]
  2. InputapplyChanges([ [ 'cherry', 1 ], [ 'banana', 2 ], [ 'apple', 3 ] ], [], [])
    Expected[ [ 'apple', 3 ], [ 'banana', 2 ], [ 'cherry', 1 ] ]
  3. InputapplyChanges([ [ 'apple', 5 ], [ 'pear', 1 ] ], [ [ 'apple', 7 ] ], [])
    Expected[ [ 'apple', 7 ], [ 'pear', 1 ] ]

Hidden tests run on Submit.