Skip to content Skip to sidebar Skip to footer

Javascript Alphabetical Grouping

I have a json array of objects that look like this: {id:'the id', name:'the name'}; and I need to loop over the array and group each object alphabetically by it's name attribute.

Solution 1:

you can loop throught your collections like this:

var groupedCollection = {};   
for(...){//loop throug collection         var firstLetter = data[i].charAt(0);
    if(groupedCollection[firstLetter] == undefined){             
        groupedCollection[firstLetter] = [];         
    }         
    groupedCollection[firstLetter].push(data[i]);     
}
//groupedCollection now contait data in the form of {a: [], b:[], etc...}

Solution 2:

Bubble sort will do this job for you. Example:

// sample arrayvar myArr = [
    {id:"00", name:"Billy"},
    {id:"00", name:"Apple"},
    {id:"00", name:"4 biscuits"},
    {id:"00", name:"Adam"},
    {id:"00", name:"Alex"},
    {id:"00", name:"4 pints"},
    {id:"00", name:"Bob"}
];

// standard bubble sort algorithmfunctionbubbleSortByName(arr) {
    for (var x = 0; x < arr.length; x++) {
        for(var y = 0; y < arr.length-1; y++) {
            // compare arr[].name.toLowerCase() i.e. b > aif(arr[y].name.toLowerCase() > arr[y+1].name.toLowerCase()) {
                var tmp = arr[y+1];
                arr[y+1] = arr[y];
                arr[y] = tmp;
            }
        }
    }
    return arr; 
}

// sort the arrayvar sortedArr = bubbleSortByName(myArr);

// print the resultsfor (var i=0; i<sortedArr.length; i++)
    document.write(sortedArr[i].name+"<br/>");

Or the same idea with an insertion sort algorithm:

// standard insertion sort algorithmfunctioninsertionSortByName(arr) {
    for(var j = 1; j < arr.length; j++) {
        var key = arr[j];
        var i = j - 1;

        while(i >= 0 && arr[i].name.toLowerCase() > key.name.toLowerCase()) {
            arr[i+1] = arr[i];
            i = i - 1;     
        }            

        arr[i+1] = key;
    }

    return arr;
}

Solution 3:

ES7 syntax

const sortAndGroup = async () => {
  const sortedData = data.sort();
  const reducedData = sortedData.reduce((items, dataElement) => {
    if (!items.find(item => item.header === dataElement.charAt(0))) {
      items.push({ header: dataElement.charAt(0) });
    }
    items.push({ name: dataElement });
    return items;
  }, []);
  return reducedData.map(item => item.header || item.name);
};


sortAndGroup().then(result =>console.log(result));

Post a Comment for "Javascript Alphabetical Grouping"