Простая задача на кодварс, все тесты код проходит, но ошибка "Uncaught TypeError: Cannot read property 'name' of undefined" не пропускает решение. В чем проблема и почему в строке под * names[names.length - 2].name
- undefiend?
Условие задачи:
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'
list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'
list([ {name: 'Bart'} ])
// returns 'Bart'
list([])
// returns ''
Мое решение:
function list(names){
let result = names.map(item => item.name).join(', ').split(' ');
result[result.length - 2] = names[names.length - 2].name + ' &'; //*
result = result.join(' ');
console.log(result);
}