I have an array with objects, and each object containing a property called name.
Now i want to have a second array containing the first letter of each name property from the first array. This first letter should be saved in a property called header if it doesn't exist yet.
I only want to have a letter to appear once, as this script is intended to be used for a list of alphabetic headers, each containing a list of names starting with the same letter.
I have created a function that uses the build-in JavaScript "filter" method, which is supposed to check if a value with this first letter already exists. But for some reason it doesn't work. The filter always returns an empty array, no matter what letter i provide.
I have been trying to figure out why my script is not working with no success. I greatly appreciate any help with this!
var fruit = [{title:"Apple"},{title:"Avocado"},{title:"Banana"},{title:"Cucumber"}];
var sections = [];
function createAlphabetSections(array) {
for(var i = 0; i < array.length; i++){
var firstLetter = array[i].title.charAt(0).toUpperCase();
var section = sections.filter(function (section) { return section.header === firstLetter;});
if(sections.length === 0){
sections.push([{header: firstLetter}]);
} else if (section.length > 0){
sections.push([{header: firstLetter}]);
}
}
}
createAlphabetSections(fruit);