0
Hi everyone. I have got an array of objects with name properties.How do i count the total number of letters in the array.
const characters = [ { name: 'Luke Skywalker', height: '172', mass: '77', eye_color: 'blue', gender: 'male', }, { name: 'Darth Vader', height: '202', mass: '136', eye_color: 'yellow', gender: 'male', }, { name: 'Leia Organa', height: '150', mass: '49', eye_color: 'brown', gender: 'female', }, { name: 'Anakin Skywalker', height: '188', mass: '84', eye_color: 'blue', gender: 'male', }, ]; That's the object right there.How can i extract only the names and then count the total number of letters supposedly using the reduce() method? This is whare i have gotten so far: const totalChars = characters.reduce((preVal, currVal) => { let joinedStr = preVal + currVal.name.split>(" "); return joinedStr; }, []);
2 Respuestas
+ 1
This will do, but it accumulate all names' length. So what should happen when a character's name contain non alphabet characters? e.g. "Champ #100"
Should the '#' and '100' be counted in?
const totalChars = characters.reduce( ( preVal, currVal ) => preVal += currVal.name.length, 0 );
+ 1
Yes all the characters must be counted in save for the white spaces e.g the space between the first name and the last name.
Thank you for your help, let me try the one you just gave me.