This is the problem I am trying to solve: 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 ''
Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.
Here is my code:
var finalName;
var notFinal;
function list(names){
var finalNames = names.forEach(returnNames);
console.log(typeof finalNames);
function returnNames() {
for (var i = 0; i<names.length; i++) {
var nameValue = Object.keys(names[i]).map(key => names[i][key])
}
}
for(var i = 0; i<finalNames.length; i++) {
if (finalNames.length / i == 1) {
finalName = "& " + finalNames[i];
}
else {
notFinal = finalNames[i] + ", ";
}
}
console.log(notFinal + finalName);
}
list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
It is stuck in the loop and finally gives an error:
TypeError: Cannot read property 'length' of undefined
at list
at /home/codewarrior/index.js:30:1
at Object.handleError
<anonymous>
How do I fix it?
You can simplify your code like below.
function list(names){
//Determine length of array (= number of names)
const len = names.length;
//Use a simple for loop to go through the array
let newNames = "";
for (i=0; i<len; i++) {
newNames += names[i].name;
if ( i<len-2 ) newNames += ", "
else if ( i<len-1 ) newNames += " & "
}
console.log(newNames);
}
list([{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'},{name: 'Homer'},{name: 'Marge'}])
list([{name: 'Bart'}, {name: 'Lisa'}]);
list([{name: 'Bart'}]);