-2

Could you help in understanding below line:

 return { ...acc, [firstLetter]: [...(acc[firstLetter] || []), cur] };

From this:

// Write a function that takes an array of strings as argument
// Group those strings by their first letter
// Return an object that contains properties with keys representing first letters
// The values should be arrays of strings containing only the corresponding strings
// For example, the array ['Alf', 'Alice', 'Ben'] should be transformed to
// { a: ['Alf', 'Alice'], b: ['Ben']}

function myFunction(arr) {
  return arr.reduce((acc, cur) => {
    const firstLetter = cur.toLowerCase().charAt(0);
    return { ...acc, [firstLetter]: [...(acc[firstLetter] || []), cur] };
  }, {});
}

Test Cases:

myFunction(['Alf', 'Alice', 'Ben'])

Expected { a: ['Alf', 'Alice'], b: ['Ben']}

myFunction(['Ant', 'Bear', 'Bird'])

Expected { a: ['Ant'], b: ['Bear', 'Bird']}

myFunction(['Berlin', 'Paris', 'Prague'])

Expected { b: ['Berlin'], p: ['Paris', 'Prague']}

trincot
  • 263,463
  • 30
  • 215
  • 251
  • Well it's transforming an array of strings into an object, with the first letter being the key, and the value being an array of all strings that start with that letter – Lk77 May 27 '22 at 13:56
  • Please focus your question on what you don't understand specifically? Is it the `return` statement, the Object literal notation, the spread syntax, the computed property name, the `||` operator, the array literal, ... be specific. – trincot May 27 '22 at 13:57
  • can you please explain me complete return statement step by step ? – sharath kumar May 27 '22 at 14:02

0 Answers0